How can I parse a simple date string and let JavaScript know that it's actually a UTC date? Currently, if I do new Date('2015-08-27') it converts it to my timezone.

  • I strongly recommend using a library for that – William Barbosa Aug 27 '15 at 14:47
  • 1
    Many different options: stackoverflow.com/questions/948532/… – Marc Aug 27 '15 at 14:48
  • I want to stay away from libraries. – Artem Kalinchuk Aug 27 '15 at 14:48
  • There is conversion, so your date might be the same .. You might not need to convert it to your timezone, what is the display of new Date('2015-08-27').toISOString() – Hacketo Aug 27 '15 at 14:48

You can do append 'T00:00:00.000Z' to make the time zone specific (Z indicates UTC)

new Date('2015-08-27' + 'T00:00:00.000Z')

Note that new Date('2015-08-27') is treated differently in ES5 (UTC) vs. ES6 (Local), so you can't expect it any correction to be work consistently if you were planning to to hard code it (i.e. don't do it)


Also, do note that your console.log might show you the local time corresponding to the UTC time the expression evaluates to (that tends to throw you off a bit if you are expecting UTC to be at the end for expression that evaluate to UTC times and your local time zone at the end for those that evaluate to your local time). For instance

new Date('2015-08-27T00:00:00.000Z')

could show

Thu Aug 27 2015 1:00:00 GMT+100

which is the same as

Thu Aug 27 2015 00:00:00 UTC

Here is what I would do.

var current = new Date();
var utcDate = new Date(current.getTime() + current.getTimezoneOffset() * 60000);

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.