0
var date = new Date('2013-04-15');
console.log(date);

Outputs:

Sun Apr 14 2013 20:00:00 GMT-0400 (EDT)

Which is -1 Day, why does Date have this behavior?

Casey Flynn
  • 13,654
  • 23
  • 103
  • 194

3 Answers3

2

These two timestamps represent the same time:

Sun Apr 14 2013 20:00:00 GMT-0400 (EDT)
Mon Apr 15 2013 00:00:00 UTC

You're getting the first, but expecting the second. The date constructor appears to take a time in UTC.

If you do:

var date = new Date('2013-04-15 EDT');
console.log(date);

Then you'll probably get the intended result


Edit: This behavior is bizarre. This code works as you intend it to:

var date = new Date('Apr 15 2013');
console.log(date);

Mon Apr 15 2013 00:00:00 GMT+XYZ
Community
  • 1
  • 1
Eric
  • 95,302
  • 53
  • 242
  • 374
  • Ahh I see, I set dates it assumes the UTC timezone? Is there anyway to set dates in the current time zone of the browser? – Casey Flynn Feb 20 '13 at 09:36
  • Any way to know the browsers timezone? – Casey Flynn Feb 20 '13 at 09:36
  • @CaseyFlynn: What are you trying to get here? Are you looking for the timestamp representing the start of the day for the timezone of the viewer looking at the page? – Eric Feb 20 '13 at 09:39
  • I have some ISO formatted dates, and my users are in different timezones. I want to show which dates are today/upcoming or past in two groups for the user in their given timezone. – Casey Flynn Feb 20 '13 at 09:53
  • @Casey: As far as I can tell, ISO formatted dates are defined to always represent UTC. Therefore, the `Date` constructor is parsing them correctly – Eric Feb 20 '13 at 09:57
  • Hmm okay, maybe I should write some kind of regex parser to create a date object in an alternate format that parses for the user's locale. – Casey Flynn Feb 20 '13 at 10:00
  • @CaseyFlynn: Why are you not storing a UTC date in the first place? – Eric Feb 20 '13 at 11:52
  • not my application. Something I'm working on for someone else and whoever came before me did it this way. – Casey Flynn Feb 20 '13 at 12:01
  • @CaseyFlynn: So if I travel to another timezone, the application starts giving me incorrect times? If you're storing local times, then you need to store the time zone associated with them. Getting that from the users browser is a bad idea. – Eric Feb 20 '13 at 12:45
  • no the application stores dates w/ corresponding time zones instead of UTC/GMT datetimes. Not ideal – Casey Flynn Feb 20 '13 at 14:16
1

You need to specify the timezone to get the output you're looking for.

An example here: Javascript date object always one day off?

Community
  • 1
  • 1
James
  • 13,092
  • 1
  • 17
  • 19
0

Because new Date() is using UTC time, the toString() use your current timezone.

If you want to print the UTC time, you should use

var date = new Date('2013-04-15');
console.log(date.toUTCString());
Steely Wing
  • 16,239
  • 8
  • 58
  • 54