How to convert String to Date with TimeZone?

后端 未结 3 1406
借酒劲吻你
借酒劲吻你 2021-01-29 06:42

I\'m trying to convert my String in Date + Timezone. I get my String from a DateTime Variable (here: xyz). My code:

Strin         


        
3条回答
  •  暖寄归人
    2021-01-29 07:06

    The input has a date - year, month, day - and an offset - the difference from UTC - but to build a java.util.Date, you also need the time: hour, minutes, seconds, fraction of seconds.

    SimpleDateFormat is terrible because it does some "magic", setting the missing fields to default values. Another problem is that the X pattern doesn't work for all Java versions, and the documentation sucks.

    You can use the new Java 8 classes, as explained. With them, you can parse the input, choose the default values to be used for the time fields and convert to java.util.Date, if that's what you need:

    DateTimeFormatter fmt = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_OFFSET_DATE)
        // set hour to midnight
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0).toFormatter();
    
    OffsetDateTime odt = OffsetDateTime.parse("2017-01-03+01:00", fmt); // 2017-01-03T00:00+01:00
    

    The OffsetDateTime will have the time set to midnight, but you can change it to whatever values you need, while with SimpleDateFormat it's not possible, because it uses internal default values and you can't control it.

    And the date and offset were correctly set to the values in the input string. You can then convert to java.util.Date if you want:

    Date date = Date.from(odt.toInstant());
    

    You can also get the individual "pieces" of the date if you want:

    // get just the date
    LocalDate localDate = odt.toLocalDate(); // 2017-01-03
    // get just the offset
    ZoneOffset offset = odt.getOffset(); // +01:00
    

    PS: the offset +01:00 is not the same thing as a timezone. See the difference here

提交回复
热议问题