How to convert String to Date with TimeZone?

后端 未结 3 1397
借酒劲吻你
借酒劲吻你 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:19

        String abc = "2017-01-03+01:00";
        TemporalAccessor parsed = DateTimeFormatter.ISO_OFFSET_DATE.parse(abc);
        LocalDate date = LocalDate.from(parsed);
        ZoneOffset offset = ZoneOffset.from(parsed);
        System.out.println("Date: " + date + "; offset: " + offset + '.');
    

    This prints:

    Date: 2017-01-03; offset: +01:00.
    

    I am using java.time, the modern Java date and time API, and recommend you do the same. The Date class is long outdated (sorry, no pun intended) and SimpleDateFormat in particular notoriously troublesome. Don’t use them. The modern API is so much nicer to work with. Only if you need a java.util.Date and/or a java.util.TimeZone for a legacy API that you cannot change, convert like this:

        Date oldfashionedDate = Date.from(date.atStartOfDay(offset).toInstant());
        TimeZone oldfashionedTimeZone = TimeZone.getTimeZone(offset);
        System.out.println("Old-fashioned date: " + oldfashionedDate
                + "; old-fashioned time-zone: " + oldfashionedTimeZone.getDisplayName() + '.');
    

    On my computer this prints:

    Old-fashioned date: Tue Jan 03 00:00:00 CET 2017; old-fashioned time-zone: GMT+01:00.
    

    I happen to be in a time zone that agrees with your offset from UTC, so it’s fairly obvious that the conversion has given the correct result. In other time zones the output will be more confusing because Date.toString() uses the JVM’s time zone setting for generating the string, but the Date will still be correct.

    A date with a time zone? Neither a LocalDate nor a Date can hold a time zone in them, so you need to have the offset information separately. Interestingly your string seems to follow a “ISO-8601-like” format for an offset date that is even represented by a built-in formatter that has ISO in its name. If Java had contained an OffsetDate or a ZonedDate class, I would have expected such a class to parse your string into just one object and even without an explicit formatter. Unfortunately no such class exists, not even in the ThreeTen-Extra project, as far as I can tell at a glance.

    Links

    • Oracle tutorial: Date Time, explaining how to use java.time.
    • ThreeTen Extra, more classes developed along with java.time.
    • EDIT: See my updated code run live on ideone.

提交回复
热议问题