使用javascript在本地时区转换日期 [英] Convert date in local timezone using javascript

查看:96
本文介绍了使用javascript在本地时区转换日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my JavaScript layer, I am receiving a timestamp which is in UTC format - and I need to convert it for the local timezone. I know that the timezone can be converted using DateFormat on the Java side, but I am looking for a reliable way to do it using only JavaScript.

任何建议都会非常感激。

Any suggestions would be very appreciated.

推荐答案

使用 getTimezoneOffset()


  1. 获取本地UTC偏移并转换为msec

  1. Obtain local UTC offset and convert to msec

localOffset = d.getTimezoneOffset() * 60000;

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

Note that a negative return value from getTimezoneOffset() indicates that the current location is ahead of UTC, while a positive value indicates that the location is behind UTC.

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

Obtain the current UTC time, by adding the local time zone offset to the local time. (localTime you will get from getTime())

// obtain UTC time in msec
utc = localTime + localOffset;


  • 获得UTC时间后,以小时为单位获取目的地城市的UTC偏移量,将其转换毫秒并将其添加到UTC时间。

  • Once you have obtained UTC time, obtain the destination city's UTC offset in hours, convert it to milliseconds and add it to UTC time.

    // 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日以来的毫秒数。显然,这不是很易读,所以我们需要进行更多的计算。

    At this point, the variable mumbai contains the local time in the city of Mumbai, India. This local time is expressed as the number of milliseconds since Jan 1 1970. Obviously, this isn't very readable, so we need to make a few more calculations.

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

    Change the time value calculated in the previous step to a human-readable date/time string by initializing a new Date() object with it, and calling the object's toLocaleString() method.

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


  • 你已经完成了!

    这篇关于使用javascript在本地时区转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆