[英]How to iterate over a date range in the following format 25-12-2012 to 31-12-2012(hyphen should be maintained) in Java?
我也想處理2月29日的leap年案件。
我嘗試了以下操作,但是在將每種時間格式轉換為dd-mm-yyyy時遇到了麻煩。
GregorianCalendar gcal = new GregorianCalendar();
SimpleDateFormat sdfd = new SimpleDateFormat("dd-MM-yyyy");
Date start = sdfd.parse("26-02-1989");
Date end = sdfd.parse("06-03-1989");
gcal.setTime(start);
while (gcal.getTime().before(end))
{
gcal.add(Calendar.DAY_OF_YEAR, 1);
System.out.println( gcal.getTime().toString());
System.out.println(gcal.);
}
我也可以在Java中使用Javascript引擎。
java.util.Date
是與此錯誤的類型。 它具有毫秒(不是天)的精度。 java.time.LocalDate
更合適。 如果需要Java <8兼容性,請使用ThreeTen 。
格式化LocalDate
:
localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
Date
對象只是一個容器,距離Unix紀元以來的毫秒數,格式為irrlevent。
Date
的toString
方法僅使用本地系統來提供其內容的可讀形式。 您不能修改此格式(直接也不應該修改,因為它將在您運行代碼的下一台計算機上更改)
如果要以給定格式顯示Date
,則應使用適當的格式化程序,例如...
System.out.println( sdfd.format(gcal.getTime()));
克里斯·馬丁的答案是正確的。 如果不比較跨時區的日期的開始/結束,則可以將類用於僅日期,而沒有任何時間或時區組成部分。
Joda-Time
和java.time
除了java.time包之外 ,您還可以使用啟發了java.time的Joda-Time 。 java.time和Joda-Time都提供LocalDate
類。 兩種框架都有其優點和缺點。 如果您對import
語句很謹慎,則可以在項目中同時使用這兩個框架。
Joda-Time 2.3中的示例代碼。
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
// LocalDate start = formatter.parseLocalDate( "26-02-1989" );
LocalDate start = new LocalDate( 1989, 2, 26 );
LocalDate stop = new LocalDate( 1989, 3, 6 );
LocalDate localDate = start;
while ( localDate.isBefore( stop ) )
{
String output = formatter.print( localDate );
localDate = localDate.plusDays( 1 );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.