How do you convert a Javascript timestamp into UTC format?

前端 未结 2 1412
执念已碎
执念已碎 2020-12-29 23:52

For example if you receive a timestamp in Javascript:

1291656749000

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

相关标签:
2条回答
  • 2020-12-30 00:22

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

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

    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))

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

    0 讨论(0)
  • 2020-12-30 00:26
    (new Date(1291656749000)).toUTCString()
    

    Is this what you're looking for?

    0 讨论(0)
提交回复
热议问题