Turning UTC milliseconds into other Time Zone

Asked

Viewed 93 times

1

I receive from a service the date in milliseconds and UTC.

I need to turn into the User Time Zone.

For that I did the following:

public static void main(String[] args) {
    // Milisegundos está em UTC...
    long time = 1457037493000L; 
    String format = "HH:mm:ss";

    SimpleDateFormat sdfUtc = new SimpleDateFormat(format, Locale.getDefault());
    sdfUtc.setTimeZone(TimeZone.getTimeZone("UTC"));

    SimpleDateFormat sdfLocal = new SimpleDateFormat(format, Locale.getDefault());
    sdfLocal.setTimeZone(TimeZone.getDefault()); // Meu TimeZone é -3...

    System.out.println("Local : "+sdfLocal.format(time));
    System.out.println("UTC : "+sdfUtc.format(time));

}

Upshot:

Location : 17:38:13
UTC: 20:38:13

In fact 17:38:13 is the time in UTC!

And the place would be 14:38:13 because my Zone Team is -3.

how do I fix the date in UTC for the user’s Time Zone?

  • 1457037493000 is equivalent to 20:38:13 in UTC - https://jsfiddle.net/mgvvsubq/ - its code is printing what it should.

  • Exactly, my question is how to print in the user’s Time Zone.

  • sdfLocal.format(time) Gives you the time in your time zone, doesn’t it? If that value is equivalent to 20:38, and you’re in UTC-0300, your time zone is 17:38. That’s not what you got when you printed it "Local : "+sdfLocal.format(time)?

1 answer

0


I got it this way by adding the getOffset timezone.

  public static long convertToTimeZoneDefault(final long time, final TimeZone zone){
        final Date localTime = new Date(time);
        final Date fromGmt = new Date(time + zone.getOffset(localTime.getTime()));
        return fromGmt.getTime();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.