Convert date in local timezone using javascript

混江龙づ霸主 提交于 2019-12-01 10:22:12

问题


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.


回答1:


Use getTimezoneOffset()

  1. Obtain local UTC offset and convert to msec

    localOffset = d.getTimezoneOffset() * 60000;
    

    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.

  2. 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;
    
  3. 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);
    

    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.

  4. 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>");
    

And you're done!



来源:https://stackoverflow.com/questions/14040556/convert-date-in-local-timezone-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!