26

For example if you receive a timestamp in Javascript:

1291656749000

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

2010/12/6 05:32:30pm

2 Answers 2

49
(new Date(1291656749000)).toUTCString()

Is this what you're looking for?

4
  • 3
    Note that the parameter sent to Date() must be in milliseconds. Feb 16, 2014 at 12:43
  • 2
    how to do just the opposite of this? i.e. convert UTC string to timestamp?
    – spyder
    Jun 2, 2015 at 10:08
  • How about convert the timestamp into GMT Jan 10, 2017 at 7:43
  • isnt it that GMT and UTC are in the same values @askingsomequestion
    – user8031952
    Jun 11, 2018 at 5:13
1

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 */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.