[英]Java date format get all dates between two date values
我正在編寫一個Java應用程序,而我剛開始使用java Date
。 我正在嘗試做的是讀取一個包含兩個日期戳的json
: 2015-05-20T17:24Z[UTC]
。 讀完兩個日期后,我只想拍攝在剛讀過的兩個日期之間帶有時間戳的對象。 誰能幫我使用這種格式嗎?
public static List<Date> getDaysBetweenDates(Date startdate, Date enddate)
{
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startdate);
while (calendar.getTime().before(enddate))
{
Date result = calendar.getTime();
dates.add(result);
calendar.add(Calendar.DATE, 1);
}
return dates;
}
上面的函數將列出兩個日期之間的所有有效日期對象
首先將String
值轉換為可比較的值...
String text = "2015-05-20T17:24Z[UTC]";
ZonedDateTime from = ZonedDateTime.parse(text, DateTimeFormatter.ISO_ZONED_DATE_TIME);
現在,(顯然),你需要一個to
日期為好,但轉換是相同的過程。 必要時,將要比較的值轉換為ZonedDateTime
對象(如上所述),並使用其功能來確定其是否在指定范圍內...
ZonedDateTime from = ...;
ZonedDateTime to = ...;
ZonedDateTime date = ...;
if (date.isAfter(from) && date.isBefore(to)) {
}
現在,這是唯一的,如果你想from
和to
日期是包容性的,你需要添加isEqual
同時檢查了from
和to
日期(但只需要匹配一個,很明顯)
現在,您應該可以使用與Joda-Time類似的功能
要解析日期,請使用SimpleDateFormat
:
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'hh:mm'Z'[ZZZ]" );
Date date = sdf.parse( "2015-05-20T17:24Z[UTC]" );
然后循環遍歷要過濾的對象並檢查object.date.compareTo(startDate) >= 0
和object.date.compareTo(endDate) <= 0
等。
或者,使用以對象的日期為鍵的排序地圖。
如MadProgrammer所說,從/到ZonedDateTime創建您的:
ZonedDateTime from = ZonedDateTime.parse(text, DateTimeFormatter.ISO_ZONED_DATE_TIME);
然后從/到創建Joda DateTime
:-
DateTimeZone zone = DateTimeZone.forID(zdt.getZone().getId());
DateTime from = new DateTime(zdt.toInstant().toEpochMilli());
然后使用Joda的Interval.contains()
檢查每個Instant是否落在該間隔內-請記住, contains()
不包括結束日期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.