4

I need to covert milliseconds to GMT date (in Android app), example:

1372916493000

When I convert it by this code:

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(millis);
Date date = cal.getTime();

the result is 07:41 07/04/2013. The result is the same when I use just:

Date date = new Date(millis);

Unfortunately the result looks incorrect, it looks like my local time. I tried to convert the same number by this service and the result is 05:41 07/04/2013, which I believe is correct. So I have two hours difference. Anybody has any suggestion / tips what's wrong with my conversion?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Michal
  • 1,324
  • 2
  • 16
  • 38
  • So, to be clear, you want the timestamp printed as a string using the GMT timezone? – Duncan Jones Jul 04 '13 at 14:38
  • Try to look in this answer: [How to convert a local date to GMT][1] [1]: http://stackoverflow.com/questions/10599109/how-to-convert-a-local-date-to-gmt – Ahiel Jul 04 '13 at 14:41
  • Did you take daylight saving time into consideration? – Roger Rapid Jul 04 '13 at 14:49
  • see here http://stackoverflow.com/questions/230126/how-to-handle-calendar-timezones-using-java – Tala Jul 04 '13 at 14:49
  • Is the milliseconds you provided represents the time in your home timezone or GMT timezone? – dumbfingers Jul 04 '13 at 14:50
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 25 '18 at 21:36

5 Answers5

14

If result which looks incorrect means System.out.println(date) then it's no surprise, because Date.toString converts date into string representation in local timezone. To see result in GMT you can use this

SimpleDateFormat df = new SimpleDateFormat("hh:ss MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = df.format(millis);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

It seemed you were messed up with your home timezone and the UTC timezone during the conversion.

Let's assume you are in London (currently London has 1 hour ahead of GMT) and the milliseconds is the time in your home timezone (in this case, London).

Then, you probably should:

Calendar cal = Calendar.getInstance();
// Via this, you're setting the timezone for the time you're planning to do the conversion
cal.setTimeZone(TimeZone.getTimeZone("Europe/London"));
cal.setTimeInMillis(1372916493000L);
// The date is in your home timezone (London, in this case)
Date date = cal.getTime();


TimeZone destTz = TimeZone.getTimeZone("GMT");
// Best practice is to set Locale in case of messing up the date display
SimpleDateFormat destFormat = new SimpleDateFormat("HH:mm MM/dd/yyyy", Locale.US);
destFormat.setTimeZone(destTz);
// Then we do the conversion to convert the date you provided in milliseconds to the GMT timezone
String convertResult = destFormat.parse(date);

Please let me know if I correctly get your point?

Cheers

dumbfingers
  • 7,001
  • 5
  • 54
  • 80
2

tl;dr

Instant.ofEpochMilli( 1_372_916_493_000L )         // Moment on timeline in UTC.

2013-07-04T05:41:33Z

…and…

Instant.ofEpochMilli( 1_372_916_493_000L )          // Moment on timeline in UTC.
       .atZone( ZoneId.of( "Europe/Berlin" ) )  // Same moment, different wall-clock time, as used by people in this region of Germany.

2013-07-04T07:41:33+02:00[Europe/Berlin]

Details

You are using troublesome old date-time classes now supplanted by the java.time classes.

java.time

If you have a count of milliseconds since the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00Z, then parse as an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.ofEpochMilli( 1_372_916_493_000L ) ;

instant.toString(): 2013-07-04T05:41:33Z

To see that same simultaneous moment through the lens of a particular region’s wall-clock time, apply a time zone (ZoneId) to get a ZonedDateTime.

ZoneId z = ZoneId.of( "Europe/Berlin" ) ; 
ZonedDateTime zdt = instant.atZone( z ) ;

zdt.toString(): 2013-07-04T07:41:33+02:00[Europe/Berlin]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

try this

public class Test{
    public static void main(String[] args) throws IOException {
        Test test=new Test();
        Date fromDate = Calendar.getInstance().getTime();
        System.out.println("UTC Time - "+fromDate);
        System.out.println("GMT Time - "+test.cvtToGmt(fromDate));
    }
    private  Date cvtToGmt( Date date )
        {
           TimeZone tz = TimeZone.getDefault();
           Date ret = new Date( date.getTime() - tz.getRawOffset() );

           // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
           if ( tz.inDaylightTime( ret ))
           {
              Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

              // check to make sure we have not crossed back into standard time
              // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
              if ( tz.inDaylightTime( dstDate ))
              {
                 ret = dstDate;
              }
           }

           return ret;
        }
}

Test Result :
UTC Time - Tue May 15 16:24:14 IST 2012
GMT Time - Tue May 15 10:54:14 IST 2012

Dennis Kriechel
  • 3,719
  • 14
  • 40
  • 62
0

Date date = cal.getTime();

returns date created via

public final Date getTime() {
    return new Date(getTimeInMillis());
}

where getTimeInMillis() returns milliseconds without any TimeZone.

I would suggest looking here for how to do what you want how-to-handle-calendar-timezones-using-java

Community
  • 1
  • 1
Tala
  • 8,888
  • 5
  • 34
  • 38
  • But is the time in milliseconds be generated based on GMT or the time zone in which the device/desktop is present? – Satyam Feb 19 '17 at 13:11