How can I convert a date to GMT?
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.
Solution 1:
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())
Solution 2:
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