DateTimeFormatter create pattern [duplicate]

依然范特西╮ 提交于 2019-12-25 01:23:21

问题


I have this date: 2008-01-10T11:00:00-05:00(date, T(separator), time, offset)

I have this: DateTimeFormatter.ofPattern("yyyy-MM-ddSEPARATORHH-mm-ssOFFSET")

I use this table to create my pattern.

But, I don't find how to note SEPARATOR(T) and OFFSET.

For OFFSET exists this: x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;, but don't know how to use x to get -08:30


回答1:


here is a little example that shows how to parse your String and receive the offset:

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.



来源:https://stackoverflow.com/questions/56834389/datetimeformatter-create-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!