Convert UTC to current locale time

后端 未结 7 1126
时光取名叫无心
时光取名叫无心 2020-11-27 03:20

I am downloading some JSON data from a webservice. In this JSON I\'ve got some Date/Time values. Everything in UTC. How can I parse this date string so the result Date objec

7条回答
  •  佛祖请我去吃肉
    2020-11-27 03:32

    java.time

    I should like to contribute the modern answer. Most of the other answers are correct and were fine answers in 2011. Today SimpleDateFormat is long outdated, and it always came with some surprises. And today we have so much better: java.time also known as JSR-310, the modern Java date and time API. This answer is for anyone who either accepts an external dependency (just until java.time comes to your Android device) or is already using Java 8 or later.

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
        String dateTimeFromServer = "2011-05-18 16:35:01";
        String localTimeToDisplay = LocalDateTime.parse(dateTimeFromServer, formatter)
                .atOffset(ZoneOffset.UTC)
                .atZoneSameInstant(ZoneId.of("Europe/Zurich"))
                .format(formatter);
    

    The result of this code snippet is what was asked for:

    2011-05-18 18:35:01
    

    Give explicit time zone if you can

    I have given an explicit time zone of Europe/Zurich. Please substitute your desired local time zone. To rely on your device’s time zone setting, use ZoneId.systemDefault(). However, be aware that this is fragile because it takes the time zone setting from the JVM, and that setting could be changed under our feet by other parts of your program or other programs running in the same JVM.

    Using java.time on Android

    I promised you an external dependency. To use the above on Android you need the ThreeTenABP, the Android edition of ThreeTen Backport, the backport of JSR-310 to Java 6 and 7. How to go about it is nicely and thoroughly explained in this question: How to use ThreeTenABP in Android Project.

提交回复
热议问题