2017-04-04 44 views
0

我能以JSON導致三種可能的格式返回日期值的API:轉換日期時間字符串如喬達日期時間(字符串)與Java 8

  1. 2017-04-30T00:00 + 02:00
  2. 2016-12-05T04:00
  3. 2016年12月5日

我需要所有三個轉換成java.time.LocalTimeDate。 Joda在DateTime對象上有一個很好的構造函數,它將所有三種格式作爲字符串並轉換它們。 DateTime dt = new DateTime(StringFromAPI);就夠了。

Java 8(java.time包)中是否有類似的功能?看來我現在首先必須將String正則表達式檢查格式,然後創建一個LocalDateTime,ZonedDateTimeLocalDate並將後者轉換爲LocalDateTime。對我來說似乎有點麻煩。有一個簡單的方法嗎?

+0

閱讀[DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) – Jens

+0

因此,第一種格式的「+02:00」應該被忽略?你在第三個假設時間是0點(午夜)嗎? –

+0

@ OleV.V。是的,是的。 –

回答

3

我提出了兩個選項,每個選項都有其優點和缺點。

一,建立一個自定義DateTimeFormatter接受你的三種可能的形式:

public static LocalDateTime parse(String dateFromJson) { 
    DateTimeFormatter format = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE) 
      .optionalStart() 
      .appendLiteral('T') 
      .append(DateTimeFormatter.ISO_LOCAL_TIME) 
      .optionalStart() 
      .appendOffsetId() 
      .optionalEnd() 
      .optionalEnd() 
      .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) 
      .toFormatter(); 
    return LocalDateTime.parse(dateFromJson, format); 
} 

一方面,它的清潔,另一方面,有人可以很容易地找到它有點棘手。對於你的問題三個樣本串它產生:

2017-04-30T00:00 
2016-12-05T04:00 
2016-12-05T00:00 

另一種選擇,嘗試了三種不同的格式轉,挑選的作品之一:

public static LocalDateTime parse(String dateFromJson) { 
    try { 
     return LocalDateTime.parse(dateFromJson); 
    } catch (DateTimeParseException e) { 
     // ignore, try next format 
    } 
    try { 
     return LocalDateTime.parse(dateFromJson, DateTimeFormatter.ISO_OFFSET_DATE_TIME); 
    } catch (DateTimeParseException e) { 
     // ignore, try next format 
    } 
    return LocalDate.parse(dateFromJson).atStartOfDay(); 
} 

我不認爲這個最漂亮的代碼,仍然有人可能認爲它比第一個選項更直接?我認爲只依靠內置的ISO格式是有質量的。你的三個示例字符串的結果與上面相同。

+0

請原諒我的好奇心@BartKooijman,你能用我的答案嗎?儘管我付出了努力,但我意識到我沒有給你任何像你描述JodaTime'DateTime'構造函數一樣簡單的東西。我沒有太多的要求接受刻度標記,因爲你的一般和誠實的反應/反饋。 –

相關問題