Android how to get time difference between two time zones in android?

后端 未结 2 1294
感动是毒
感动是毒 2021-01-02 08:30

I need to get time difference between two dates in different time zones. Currently I am doing this:

Calendar c1=Calendar.getInstance(TimeZone.getTimeZone(\"E         


        
相关标签:
2条回答
  • 2021-01-02 08:45

    Jon is close, but due to character restrictions I can't edit his answer. This is the same code but with "EDT" changed to "EST" for Eastern Standard Time.

    long currentTime = System.currentTimeMillis();
    int edtOffset = TimeZone.getTimeZone("EST").getOffset(currentTime);
    int gmtOffset = TimeZone.getTimeZone("GMT").getOffset(currentTime);
    int hourDifference = (gmtOffset - edtOffset) / (1000 * 60 * 60);
    String diff = hourDifference + " hours";
    

    But this solution makes a major assumption that TimeZone.getAvailableIDs() has within it's string array both "EST" and "GMT". If that method doesn't contain those timezone strings it will come back as 0 offset.

    0 讨论(0)
  • 2021-01-02 09:06

    getTimeInMillis() returns the number of milliseconds since the epoch in UTC. In other words, the time zone is irrelevant to it.

    I suspect you actually want:

    long currentTime = System.currentTimeMillis();
    int edtOffset = TimeZone.getTimeZone("EDT").getOffset(currentTime);
    int gmtOffset = TimeZone.getTimeZone("GMT").getOffset(currentTime);
    int hourDifference = (gmtOffset - edtOffset) / (1000 * 60 * 60);
    String diff = hourDifference + " hours";
    
    0 讨论(0)
提交回复
热议问题