Coltech
Coltech

Reputation: 1710

Why is Javascript Changing My Date?

I am getting a date value back from an ajax request which looks like the following:

"2013-08-08T00:00:00"

Well that's no good, so I parse just the date:

mydate = mydate.substring(0,10);

Which gives me:

"2013-08-08"

Great, now I'll just make it a real date:

mydate = new Date(mydate.substring(0,10))

And get:

Wed Aug 07 2013 20:00:00 GMT-0400 (Eastern Daylight Time)

Huh? Why did I lose one day?

Upvotes: 0

Views: 112

Answers (3)

jrbeverly
jrbeverly

Reputation: 1621

You have an interesting situation here indeed, this is caused by when you create a Date object, unless you specify a timezone offset, it assumes that your date input is in UTC time, then converts it. This is only because you entered your value with '-' instead of '/'

EDIT: Correction, I believe your date may be taken in as UTC time, then converted to the appropriate EDT time. This would explain why setting the exactly values or using '/' returns a different result. '/' probably denotes EDT time, while '-' denotes UTC time.

See:

var asString = "2013-08-08T00:00:00" var mydate =
asString.substring(0,10);

var cDate1 = new Date(mydate);

var cDate2 = new Date(mydate.replace('-', '/'));

var asSplit = mydate.split('-'); 
var cDate3 = new Date(asSplit);

alert(cDate1 + "\n" + cDate2 + "\n" + cDate3);

Which produces the following:

Wed Aug 07 2013 20:00:00 GMT-0400 (Eastern Daylight Time)
Thu Aug 08 2013 00:00:00 GMT-0400 (Eastern Daylight Time)
Thu Aug 08 2013 00:00:00 GMT-0400 (Eastern Daylight Time)

Where the cases are:

  • Standard
  • Replace '-' with '/'
  • Separate into Year/Month/Day

You can see it in action here

EDIT: Noted an error pointed out by loxxy

Upvotes: 3

loxxy
loxxy

Reputation: 13151

This should work :

new Date("2013-08-08".split("-"))

So In your case :

new Date(mydate.substring(0,10).split("-"))

Upvotes: 0

Paul Adamczyk
Paul Adamczyk

Reputation: 1

I would suggest making it 2013,08,08 instead seems it doesn't like the hyphens

http://www.w3schools.com/jsref/jsref_obj_date.asp

Date object takes

var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Upvotes: 0

Related Questions