DateTimeFormatter create pattern [duplicate]

2019-08-17 23:24发布

问题:

This question already has an answer here:

  • How to get start and end range from list of timestamps? 2 answers
  • Converting ISO 8601-compliant String to java.util.Date 26 answers

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.