Milliseconds to Date in GMT in Java

后端 未结 5 852
一个人的身影
一个人的身影 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

提交回复
热议问题