Milliseconds to Date in GMT in Java

后端 未结 5 833
一个人的身影
一个人的身影 2020-12-06 08:19

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

1372916493000

When I convert it by this code:

Calendar cal          


        
相关标签:
5条回答
  • 2020-12-06 08:58

    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

    0 讨论(0)
  • 2020-12-06 08:59

    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);
    
    0 讨论(0)
  • 2020-12-06 09:08

    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?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    0 讨论(0)
  • 2020-12-06 09:09

    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

    0 讨论(0)
  • 2020-12-06 09:11

    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

    0 讨论(0)
提交回复
热议问题