DateTimeFormatter 创建模式

DateTimeFormatter create pattern

我有这个日期:2008-01-10T11:00:00-05:00(date, T(separator), time, offset)

我有这个:DateTimeFormatter.ofPattern("yyyy-MM-ddSEPARATORHH-mm-ssOFFSET")

我用这个 table 来创建我的图案。

但是,我找不到如何记录 SEPARATOR(T) 和 OFFSET。

对于 OFFSET 存在这个:x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;,但不知道如何使用 x 来获得 -08:30

这里有一个小例子,展示了如何解析您的 String 并接收偏移量:

public static void main(String[] args) {
    // this is what you have, a datetime String with an offset
    String dateTime = "2008-01-10T11:00:00-05:00";
    // create a temporal object that considers offsets in time
    OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTime);
    // just print them in two different formattings
    System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    System.out.println(offsetDateTime.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")));
    // get the offset from the object
    ZoneOffset zonedOffset = offsetDateTime.getOffset();
    // get its display name (a String representation)
    String zoneOffsetString = zonedOffset.getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault());
    // and print the result
    System.out.println("The offset you want to get is " + zoneOffsetString);
}

Please pay attention to the code comments, they explain what is done. Printing the OffsetDateTime two times in the middle of the code is just done in order to show how you can deal with a single datetime object along with different formatters.