Android:获得两个时区之间的秒数时差

时间:2017-06-22 12:34:23

标签: android

我是Android新手。

如何在Android中以秒为单位获得两个时区之间的差异?

例如,亚洲/德黑兰(+4:30)和亚洲/巴格达(+3:00)之间的差异是5400秒(1:30小时)。

2 个答案:

答案 0 :(得分:2)

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//you should now have timezone calculated in miliseconds
df1.setTimeZone(TimeZone.getTimeZone("<timezone_you_want>"));
df2.setTimeZone(TimeZone.getTimeZone("<timezone_you_want>"));

//do the difference and calculate hours
long diffInMillisec = df1 - df2;
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);

答案 1 :(得分:0)

解决问题:

int loc2 = TimeZone.getTimeZone("Asia/Tehran").getRawOffset();
int loc1 = TimeZone.getTimeZone("UTC").getRawOffset();
return (loc2 - loc1) / 1000;

更准确地计算(夏日光照时间):

public int getTimezoneDifferenceInSecond(String zone1, String zone2) {
    Date now = new Date();
    TimeZone timeZone1 = TimeZone.getTimeZone(zone1);
    TimeZone timeZone2 = TimeZone.getTimeZone(zone2);

    int currentOffsetFromUTC = timeZone1.getRawOffset() + (timeZone1.inDaylightTime(now) ? timeZone1.getDSTSavings() : 0);
    int serverOffsetFromUTC = timeZone2.getRawOffset() + (timeZone2.inDaylightTime(now) ? timeZone2.getDSTSavings() : 0);
    return (serverOffsetFromUTC - currentOffsetFromUTC) / 1000;
}