Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a date to GMT?

Tags:

javascript

How to convert date of different timezones to GMT 0? Let say I have dates like this

Fri Jan 20 2012 11:51:36 GMT-0500 Fri Jan 20 2012 11:51:36 GMT-0300 Fri Jan 20 2012 11:51:36 GMT+0500 

to

Fri Jan 20 2012 06:51:36 GMT Fri Jan 20 2012 08:51:36 GMT Fri Jan 20 2012 16:51:36 GMT 

these are dates I am getting via new Date().toString() on different timezones. Is there any js method to detect timezone and convert accordingly?

EDIT: The second three dates are not the GMT converted times of the first three. For example, Fri Jan 20 2012 11:51:36 GMT-0500 in GMT is Fri Jan 20 2012 16:51:36 GMT not Fri Jan 20 2012 06:51:36 GMT. GMT-0500 is behind GMT, not ahead, so you have to add the offset to get GMT, not subtract it.

like image 695
coure2011 Avatar asked Jan 20 '12 16:01

coure2011


People also ask

How do I convert a date time field for any TimeZone?

Calendar calendar = new GregorianCalendar(TimeZone. getTimeZone("GMT")); DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); formatter. setTimeZone(TimeZone.

How do I find my GMT timestamp?

Use the getTime() method to get a GMT timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. UTC shares the same current time with GMT.

How do you convert date to UTC format?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.


2 Answers

Matt Johnson-Pint's answer is much better than this one was.

console.log(new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString())
like image 61
Jivings Avatar answered Sep 19 '22 02:09

Jivings


You can simply use the toUTCString (or toISOString) methods of the date object.

Example:

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()  // Output:  "Fri, 20 Jan 2012 16:51:36 GMT" 

If you prefer better control of the output format, consider using a library such as date-fns or moment.js.

Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.

11:51:36 -0300  ==  14:51:36Z 
like image 20
Matt Johnson-Pint Avatar answered Sep 21 '22 02:09

Matt Johnson-Pint