如何将 Javascript 时间戳转换为 UTC 格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4380469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:11:05  来源:igfitidea点击:

How do you convert a Javascript timestamp into UTC format?

javascriptdatetime

提问by ectype

For example if you receive a timestamp in Javascript:

例如,如果您在 Javascript 中收到时间戳:

1291656749000

1291656749000

How would you create a function to convert the timestamp into UTC like:

您将如何创建一个将时间戳转换为 UTC 的函数,例如:

2010/12/6 05:32:30pm

2010/12/6 05:32:30pm

回答by meder omuraliev

(new Date(1291656749000)).toUTCString()

Is this what you're looking for?

这是你要找的吗?

回答by kennebec

I would go with (new Date(integer)).toUTCString(),

我会用(new Date(integer)).toUTCString()

but if you have to have the 'pm', you can format it yourself:

但是如果你必须有'pm',你可以自己格式化:

function utcformat(d){
    d= new Date(d);
    var tail= 'GMT', D= [d.getUTCFullYear(), d.getUTCMonth()+1, d.getUTCDate()],
    T= [d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds()];
    if(+T[0]> 12){
        T[0]-= 12;
        tail= ' pm '+tail;
    }
    else tail= ' am '+tail;
    var i= 3;
    while(i){
        --i;
        if(D[i]<10) D[i]= '0'+D[i];
        if(T[i]<10) T[i]= '0'+T[i];
    }
    return D.join('/')+' '+T.join(':')+ tail;
}

alert(utcformat(1291656749000))

警报(utcformat(1291656749000))

/* returned value: (String) 2010/12/06 05:32:29 pm GMT */

/* 返回值:(字符串)2010/12/06 05:32:29 pm GMT */