本文介绍了javascript toISOString() 忽略时区偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在尝试将 Twitter 日期时间转换为本地 iso 字符串(对于prettyDate) 2 天.我只是没有正确理解当地时间..

I am trying to convert Twitter datetime to a local iso-string (for prettyDate) now for 2 days. I'm just not getting the local time right..

我使用以下函数:

function getLocalISOTime(twDate) {
    var d = new Date(twDate);
    var utcd = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(),
        d.getMinutes(), d.getSeconds(), d.getMilliseconds());

    // obtain local UTC offset and convert to msec
    localOffset = d.getTimezoneOffset() * 60000;
    var newdate = new Date(utcd + localOffset);
    return newdate.toISOString().replace(".000", "");
}

在 newdate 中一切正常,但 toISOString() 再次将其扔回原始时间...任何人都可以帮助我从 Twitterdate 格式中获取 iso 中的当地时间:2012 年 5 月 31 日星期四 08:33:41 +0000

in newdate everything is ok but the toISOString() throws it back to the original time again...Can anybody help me get the local time in iso from the Twitterdate formatted as:Thu, 31 May 2012 08:33:41 +0000

推荐答案

moment.js 很棒,但有时您不想为简单的事情拉取大量依赖项.

moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.

以下也适用:

    var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
    var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);

    console.log(localISOTime)  // => '2015-01-26T06:40:36.181'

slice(0, -1) 去掉了代表祖鲁时区的尾随 Z,可以用你自己的时区替换.

The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.

这篇关于javascript toISOString() 忽略时区偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:05