2013-01-21 3 views
2

안녕하세요 어떤 라이브러리도 사용하지 않고 기간을 반복하고 싶습니다. 2005 년 1 월 18 일부터 시작하여 yyyy/M/d로 포맷하고 싶고 현재 날짜까지 하루 간격으로 반복하고 싶습니다. 시작 날짜의 형식을 지정했는데 캘린더 개체에 추가하고 반복 할 수있는 방법을 모르겠습니다. 나는 누군가가 도울 수 있는지 궁금해하고 있었다. 감사합니다라이브러리를 사용하지 않고 날짜 범위를 반복하십시오. Java

String newstr = "2005/01/18"; 
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d"); 

답변

6
Date date = format1.parse(newstr); 
Calendar calendar = new GregorianCalendar(); 
calendar.setTime(date); 
while (someCondition(calendar)) { 
    doSomethingWithTheCalendar(calendar); 
    calendar.add(Calendar.DATE, 1); 
} 
1

사용 SimpleDateFormatDate 객체로 문자열을 구문 분석 또는 문자열로 Date 객체를 포맷합니다.

날짜 계산에는 클래스 Calendar을 사용하십시오. 하루 일정과 같이 일정을 앞당길 수있는 add 방법이 있습니다.

위에서 언급 한 클래스의 API 문서를 참조하십시오.

또는 Joda Time 라이브러리를 사용하면 이러한 일이 더 쉬워집니다. (표준 Java API의 DateCalendar 클래스에는 설계 문제가 많으며 Joda Time만큼 강력하지 않습니다.

-2

Java 및 실제로 많은 시스템은 UTC 1970 년 1 월 12 일 오전 12 시부 터 시간을 밀리 초 단위로 저장합니다. 이 숫자는 long으로 정의 할 수 있습니다.

//to get the current date/time as a long use 
long time = System.currentTimeMillis(); 

//then you can create a an instance of the date class from this time. 
Date dateInstance = new Date(time); 

//you can then use your date format object to format the date however you want. 
System.out.println(format1.format(dateInstance)); 

//to increase by a day, notice 1000 ms = 1 second, 60 seconds = 1 minute, 
//60 minutes = 1 hour 24 hours = 1 day so add 1000*60*60*24 
//to the long value representing time. 
time += 1000*60*60*24; 

//now create a new Date instance for this new time value 
Date futureDateInstance = new Date(time); 

//and print out the newly incremented day 
System.out.println(format1.format(futureDateInstance)); 
+0

날짜에 날짜를 추가하는 것은 좋지 않습니다. 하루가 25 시간 지속되는 DST로 인해 적어도 일 년에 한 번 실패합니다. –

+0

그것은 시간을 늘리는 방법의 예일뿐 endall 고정 솔루션은 아닙니다. 필요한 경우 더 많은 요인을 고려할 수 있습니다. –

+0

그리고 GregorianCalendar를 다시 구현 하시겠습니까? 아뇨, 미안 해요. 날짜 aruthmetics는 올바르게하기가 매우 어렵습니다. 그것은 정말로 당신이 혼자하고 싶지 않은 것입니다. –

관련 문제