I need to generate a javascript Date
from a UTC date string with the format YYYY-MM-DD
. Here is an example:
var date = new Date('2018-01-31');
The date this creates is:
Tue Jan 30 2018 19:00:00 GMT-0500 (Eastern Standard Time)
Given the time zone offset, the date is yesterday.
How can I create a javascript Date that assumes the timeless input is UTC?
You can use Date.UTC .
This is an example from https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
var utcDate1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
var utcDate2 = new Date(Date.UTC(0, 0, 0, 0, 0, 0));
console.log(utcDate1.toUTCString());
// expected output: Fri, 02 Feb 1996 03:04:05 GMT
console.log(utcDate2.toUTCString());
// expected output: Sun, 31 Dec 1899 00:00:00 GMT
So you get this as solution:
var test = "2018-01-31";
var year = test.substr(0,4);
var month = test.substr(5,2) -1;
var day = test.substr(8,2);
var utcDate1 = new Date(Date.UTC(year,month,day));
alert(utcDate1.toUTCString());
// expected output:Wed, 31 Jan 2018 00:00:00 GMT
You can use a combination of Date.UTC
, split
and the spread
(operator syntax...
is not an operator):
var convertedDate = '2018-01-31'.split('-');
convertedDate[1] = convertedDate[1] - 1 // Date.UTC expects a value from 0-11
var date = new Date(Date.UTC(...convertedDate))
console.log(date.toDateString());
It is important to note that Date.UTC
expects a month form 0-11 (for some reason)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With