0

I'm using some library that won't sort objects by a string value but will sort them by date. I have months like '2008-04' and I should be able to convert them to Javascript dates for the first of the appropriate month. But my local timezone screws things up:

 new Date('2008-04')
 Mon Mar 31 2008 20:00:00 GMT-0400 (EDT)

This is probably a duplicate of How do you convert a JavaScript date to UTC?, but maybe there's a simpler answer for my particular use case than the ones there?

BTW, I get the same answer by specifying the first of the month:

 new Date('2008-04-01')
 Mon Mar 31 2008 20:00:00 GMT-0400 (EDT)

I'm using ES6. I don't suppose that makes it any more straightforward?

Community
  • 1
  • 1
Sigfried
  • 2,943
  • 3
  • 31
  • 43
  • you can take a look at some production-ready library, like http://momentjs.com/ - maybe it has this problem solved already – llamerr Apr 07 '16 at 11:53
  • Yeah, I've used momentjs before. It's pretty big for solving a tiny problem I'm too lazy to solve in 5 lines of javascript. – Sigfried Apr 07 '16 at 11:55
  • Possible duplicate of [How do you convert a JavaScript date to UTC?](http://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc) – Sigfried Apr 07 '16 at 13:24

2 Answers2

1

Add '-01T00:00:00Z' to the string with part of ISO 6801 date:

document.write(new Date('2008-04' + '-01T00:00:00Z'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • `new Date('2008-04-01') --> Mon Mar 31 2008 20:00:00 GMT-0400 (EDT)` – Sigfried Apr 07 '16 at 11:49
  • you can treat the date string as sting for sorting. iso dates are always localized and depending on yout time zone, you get dates in the past. but you can stil sort with this dates, because the errror is always the same on every date. – Nina Scholz Apr 07 '16 at 12:11
0

I misunderstood. The date is already UTC, it's just when I display it as a string locally that it gets converted to my local timezone. So the answer is just

 new Date('2008-04').toUTCString()
 "Tue, 01 Apr 2008 00:00:00 GMT"

or

 new Date('2008-04').toISOString()
 "2008-04-01T00:00:00.000Z"
Sigfried
  • 2,943
  • 3
  • 31
  • 43