문제

I have a time variable in GMT and I will convert in UTC. I post my code:

long mytime = 1376824500000;
Date date = new Date(mytime);
String time = new SimpleDateFormat("HH:mm").format(date);

This return "13:15" in some device, but I would like to have always UTC date: "11:15". How can I do that?

도움이 되었습니까?

해결책

It's not clear what difference you're expecting between UTC and GMT - for the purposes we're talking here, they're equivalent. (They're not quite technically the same, but...)

In terms of formatting, you just need to set the time zone on your formatter:

// TODO: Consider setting a locale explicitly
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
String time = format.format(date);

다른 팁

Try this:

long mytime = 1376824500000;
Date date = new Date(mytime);
SimpleDateFormat formater = = new SimpleDateFormat("HH:mm");
formater .setTimeZone(TimeZone.getTimeZone("GMT"));
String time formater.format(date);

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

import java.time.Instant;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.ofEpochMilli(1_376_824_500_000L);
        OffsetDateTime odtUtc = instant.atOffset(ZoneOffset.UTC);
        LocalTime time = odtUtc.toLocalTime();
        System.out.println(time);

        // If you want the time with timezone offset
        OffsetTime ot = odtUtc.toOffsetTime();
        System.out.println(ot);
    }
}

Output:

11:15
11:15Z

ONLINE DEMO

The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top