Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a JavaScript date to UTC?

Suppose a user of your website enters a date range.

2009-1-1 to 2009-1-3 

You need to send this date to a server for some processing, but the server expects all dates and times to be in UTC.

Now suppose the user is in Alaska or Hawaii or Fiji. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this:

2009-1-1T8:00:00 to 2009-1-4T7:59:59 

Using the JavaScript Date object, how would you convert the first "localized" date range into something the server will understand?

like image 389
dthrasher Avatar asked Jun 04 '09 03:06

dthrasher


People also ask

How do you convert a date to UTC format?

To convert a JavaScript date object to a UTC string, you can use the toUTCString() method of the Date object. The toUTCString() method converts a date to a string, using the universal time zone. Alternatively, you could also use the Date. UTC() method to create a new Date object directly in UTC time zone.

Is JavaScript new date in UTC?

getTime() returns the number of milliseconds since 1970-01-01. If you create a new Date using this number, ex: new Date(Date. getTime()); it will be UTC, however when you display it (ex: through the chrome dev tools console) it will appear to be your local timezone.

How do I get a UTC timestamp in JavaScript?

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

How do you convert date and time to UTC in node js?

Use the toUTCString() method to convert local time to UTC, e.g. new Date(). toUTCString() . The toUTCString() method converts a date to a string, using the UTC time zone.


2 Answers

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

Source: MDN web docs

The format you need is created with the .toISOString() method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:

This will give you the ability to do what you need:

var isoDateString = new Date().toISOString(); console.log(isoDateString);

For Timezone work, moment.js and moment.js timezone are really invaluable tools...especially for navigating timezones between client and server javascript.

like image 24
Will Stern Avatar answered Oct 15 '22 14:10

Will Stern


Simple and stupid

var date = new Date();  var now_utc =  Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());   return new Date(now_utc); 
like image 81
DrunkCoder Avatar answered Oct 15 '22 12:10

DrunkCoder