Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a Javascript timestamp into UTC format?

Tags:

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

like image 886
ectype Avatar asked Dec 07 '10 18:12

ectype


People also ask

How do you convert a JavaScript date to UTC?

The Javascript date can be converted to UTC by using functions present in Javascript Date object. The toUTCString() method is used to convert a Date object into a string, according to universal time. The toGMTString() returns a string which represents the Date based on the GMT (UT) time zone.

How do I convert a timestamp to UTC?

Getting the UTC timestamp Use the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.

Is JavaScript date in UTC?

The JavaScript Date is always stored as UTC, and most of the native methods automatically localize the result.

What is UTC time zone in JavaScript?

UTC() method in JavaScript is used to return the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time. The UTC() method differs from the Date constructor in two ways: Date. UTC() uses universal time instead of the local time.


2 Answers

(new Date(1291656749000)).toUTCString() 

Is this what you're looking for?

like image 168
meder omuraliev Avatar answered Oct 04 '22 02:10

meder omuraliev


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

like image 41
kennebec Avatar answered Oct 04 '22 02:10

kennebec