2016-08-03 61 views
0

我想我只是希望這給我一個解析異常,但它沒有。如果日期無效,我希望解析失敗。 (這就是我需要知道的)ZonedDateTime:我想解析()在無效日期失敗

添加註意:將2月30日作爲無效日期:(實際上,我需要做的是接收5個字符串;年,月,日,小時,分鐘,其中I組裝成str(下面),看他們是否走到一起爲有效的日期時間(在ZONE_ID)。

String ZONE_NAME = "America/Los_Angeles"; 
ZoneId ZONE_ID = ZoneId.of(ZONE_NAME); 
String ldtfPattern = "yyyy/MM/dd HH:mm"; 
DateTimeFormatter localDateTimeFormatter = 
     DateTimeFormatter.ofPattern(ldtfPattern); 

String str = "2016/02/30 21:09"; 

try { 
    zdt = ZonedDateTime.parse(str, localDateTimeFormatter().withZone(ZONE_ID)); 
} catch(DateTimeParseException e) { 
    return null; 
} 
return zdt; 

ZDT的字符串值之後上述解析是 2016-02-29T21:09-08:00[America/Los_Angeles]

+1

您在那裏的'str'匹配格式,所以不會拋出異常。如果你把它改成不是的東西(比如'「2016-02-30 21:09」'),你確實會得到一個'DateTimeParseException'。 – Mureinik

+0

@Mureinik我爲此得到了降低?這是2月30日,這是無效的,我希望這失敗。或者我想知道這一點。 –

+1

哦,好點! Downvote刪除,但我建議編輯它的問題來高亮它。 – Mureinik

回答

2

甲小鳥告訴我試着用withResolverStyle()設置爲STRICT。有了這個,唯一的其他tric k我需要使這項工作是合併era into my year。因此,改變上述是:

String ldtfPattern = "uuuu/MM/dd HH:mm"; 

zdt = ZonedDateTime.parse(str, 
       getLocalDateTimeFormatter().withZone(ZONE_ID).withResolverStyle(ResolverStyle.STRICT)); 

,這是爲我工作。

相關問題