Convert Date/Time for given Timezone - java

前端 未结 16 2437
孤城傲影
孤城傲影 2020-11-22 12:36

I want to convert this GMT time stamp to GMT+13:

2011-10-06 03:35:05

I have tried about 100 different combinations of DateFormat, TimeZone,

16条回答
  •  Happy的楠姐
    2020-11-22 12:56

    I should like to provide the modern answer.

    You shouldn’t really want to convert a date and time from a string at one GMT offset to a string at a different GMT offset and with in a different format. Rather in your program keep an instant (a point in time) as a proper date-time object. Only when you need to give string output, format your object into the desired string.

    java.time

    Parsing input

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .append(DateTimeFormatter.ISO_LOCAL_DATE)
                .appendLiteral(' ')
                .append(DateTimeFormatter.ISO_LOCAL_TIME)
                .toFormatter();
    
        String dateTimeString = "2011-10-06 03:35:05";
        Instant instant = LocalDateTime.parse(dateTimeString, formatter)
                .atOffset(ZoneOffset.UTC)
                .toInstant();
    

    For most purposes Instant is a good choice for storing a point in time. If you needed to make it explicit that the date and time came from GMT, use an OffsetDateTime instead.

    Converting, formatting and printing output

        ZoneId desiredZone = ZoneId.of("Pacific/Auckland");
        Locale desiredeLocale = Locale.forLanguageTag("en-NZ");
        DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern(
                "dd MMM uuuu HH:mm:ss OOOO", desiredeLocale);
    
        ZonedDateTime desiredDateTime = instant.atZone(desiredZone);
        String result = desiredDateTime.format(desiredFormatter);
        System.out.println(result);
    

    This printed:

    06 Oct 2011 16:35:05 GMT+13:00

    I specified time zone Pacific/Auckland rather than the offset you mentioned, +13:00. I understood that you wanted New Zealand time, and Pacific/Auckland better tells the reader this. The time zone also takes summer time (DST) into account so you don’t need to take this into account in your own code (for most purposes).

    Since Oct is in English, it’s a good idea to give the formatter an explicit locale. GMT might be localized too, but I think that it just prints GMT in all locales.

    OOOO in the format patterns string is one way of printing the offset, which may be a better idea than printing the time zone abbreviation you would get from z since time zone abbreviations are often ambiguous. If you want NZDT (for New Zealand Daylight Time), just put z there instead.

    Your questions

    I will answer your numbered questions in relation to the modern classes in java.time.

    Is possible to:

    1. Set the time on an object

    No, the modern classes are immutable. You need to create an object that has the desired date and time from the outset (this has a number of advantages including thread safety).

    1. (Possibly) Set the TimeZone of the initial time stamp

    The atZone method that I use in the code returns a ZonedDateTime with the specified time zone. Other date-time classes have a similar method, sometimes called atZoneSameInstant or other names.

    1. Format the time stamp with a new TimeZone

    With java.time converting to a new time zone and formatting are two distinct steps as shown.

    1. Return a string with new time zone time.

    Yes, convert to the desired time zone as shown and format as shown.

    I found that anytime I try to set the time like this:

    calendar.setTime(new Date(1317816735000L));
    

    the local machine's TimeZone is used. Why is that?

    It’s not the way you think, which goes nicely to show just a couple of the (many) design problems with the old classes.

    • A Date hasn’t got a time zone. Only when you print it, its toString method grabs your local time zone and uses it for rendering the string. This is true for new Date() too. This behaviour has confused many, many programmers over the last 25 years.
    • A Calender has got a time zone. It doesn’t change when you do calendar.setTime(new Date(1317816735000L));.

    Link

    Oracle tutorial: Date Time explaining how to use java.time.

提交回复
热议问题