【问题标题】:Convert date in local timezone using javascript使用javascript在本地时区转换日期
【发布时间】:2012-12-26 12:26:28
【问题描述】:

在我的 JavaScript 层中,我收到了一个 UTC 格式的 timestamp - 我需要将其转换为 本地时区。我知道可以在 Java 端使用 DateFormat 转换时区,但我正在寻找一种仅使用 JavaScript 的可靠方法。

任何建议将不胜感激。

【问题讨论】:

标签: javascript timezone date-format


【解决方案1】:

使用 getTimezoneOffset()

  1. 获取本地 UTC 偏移量并转换为毫秒

    localOffset = d.getTimezoneOffset() * 60000;
    

    请注意,getTimezoneOffset() 的负返回值表示当前位置早于 UTC,而正值表示该位置晚于 UTC。

  2. 通过将本地时区偏移量添加到本地时间来获取当前的 UTC 时间。 (localTime 你将从 getTime() 获得)

    // obtain UTC time in msec
    utc = localTime + localOffset;
    
  3. 获取 UTC 时间后,获取目的地城市的 UTC 时间偏移量,以小时为单位,将其转换为毫秒并添加到 UTC 时间。

    // obtain and add destination's UTC time offset
    // for example, Mumbai(India) 
    // which is UTC + 5.5 hours
    offset = 5.5;   
    mumbai = utc + (3600000*offset);
    

    此时,变量 mumbai 包含印度孟买市的当地时间。这个本地时间表示为自 1970 年 1 月 1 日以来的毫秒数。显然,这不是很可读,因此我们需要进行一些计算。

  4. 通过用它初始化一个新的 Date() 对象并调用该对象的 toLocaleString() 方法,将上一步中计算的时间值更改为人类可读的日期/时间字符串。

    // convert msec value to date string
    nd = new Date(mumbai); 
    document.writeln("Mumbai time is " + nd.toLocaleString() + "<br>");
    

你就完成了!

【讨论】:

  • 使用上述方法获取偏移量不可靠。这可能会忽略夏令时。我已经有客户端时区和 UTC 日期时间戳。现在我要转换为计算出的时区。
猜你喜欢
  • 2016-04-07
  • 2020-12-28
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 2019-03-20
  • 2014-01-28
  • 2020-09-08
  • 2020-05-24
相关资源
最近更新 更多