首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于TimeZones的计算时间

基于TimeZones的计算时间
EN

Stack Overflow用户
提问于 2012-10-22 09:18:18
回答 1查看 175关注 0票数 3

当我从印度本地服务器上运行时,我的代码将正确计算日期和时间,包括dayLightSaving时间。但是,当我从美国服务器运行相同的代码时,我得到的时间比timeZoneId提前了一个小时,因为它没有使用DST。

代码语言:javascript
复制
TimeZone tz = TimeZone.getTimeZone("America/Phoenix");
Date currTime = getDateByTZ(new Date(), tz);
System.out.println("currTime" + currTime);

public static Date getDateByTZ(Date d, TimeZone tz) throws Exception {

    if (tz == null) {
        tz = TimeZone.getDefault();
    }
    Integer tzOffSet = tz.getRawOffset();
    Integer tzDST = tz.getDSTSavings();
    Integer defOffSet = TimeZone.getDefault().getRawOffset();
    Integer defDST = TimeZone.getDefault().getDSTSavings();
    Calendar cal = Calendar.getInstance(tz);
    cal.setTime(d);
    if (tz.inDaylightTime(d)) {
        cal.add(Calendar.MILLISECOND, -defOffSet);
        cal.add(Calendar.MILLISECOND, -defDST);
        cal.add(Calendar.MILLISECOND, +tzOffSet);
        cal.add(Calendar.MILLISECOND, +tzDST);
    } else {
        cal.add(Calendar.MILLISECOND, -defOffSet);
        cal.add(Calendar.MILLISECOND, tzOffSet);
    }
    return cal.getTime();
}

本地服务器的结果:

当前时间:10月22日01:52:21 IST 2012

USserver的结果:

当前时间:2012年10月22日:52:21

EN

回答 1

Stack Overflow用户

发布于 2012-10-22 09:25:18

这段代码没什么意义。在另一个时区中使用日期对象不需要转换。它代表了一个普遍的瞬间。

有意义的是在显示(或格式化为字符串)日期对象时使用时区。在这种情况下,您应该简单地在DateFormat实例上设置时区,组成日期的通用瞬间将被格式化,以便对给定的时区有意义。

代码语言:javascript
复制
Date now = new Date(); // now, whatever the timezone is

DateFormat df = DateFormat.getDateTimeInstance();

df.setTimeZone(TimeZone.getDefault());
System.out.println("Now displayed in the default time zone : " + df.format(now));
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Now displayed in the New York time zone : " + df.format(now));
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13008245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档