user1073113
user1073113

Reputation: 25

Javascript Date.getTime() format problems

Hi Guys Its just bugging me.

I have here two dates w/c are the same but in different formats.

var date1 = new Date('1985-04-15'); //April 04, 1985
var date2 = new Date('04/15/1985'); //April 04, 1985

now the problem is when converting this two to "time"

date1.getTime() would output 482371200000 //
date2.getTime() would output 482342400000 //

anyone could explain me why this two outputs different values? does the "/" or "-" affects how the date was converted to time?

Upvotes: 1

Views: 1691

Answers (2)

SajithNair
SajithNair

Reputation: 3867

Explanation is give here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

new Date() or Date.parse() assumes the timezone, if timezone is not specified in the input string. Assumption may be wrong for some string formats.

You can always get the UTC time using Date.UTC

var date1 = new Date('1985-04-15'); //April 04, 1985
var date2 = new Date('04/15/1985'); //April 04, 1985

Now instead of using date1.getTime() use Date.UTC

Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()) //482371200000
Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()) //482371200000

Upvotes: 0

Damon Smith
Damon Smith

Reputation: 1790

You can plug the numbers back into the Date constructor to see what dates it's generating, like this:

new Date('1985-04-15').getTime();
482371200000
new Date('04/15/1985').getTime()
482335200000
new Date(482335200000)
Mon Apr 15 1985 00:00:00 GMT+1000 (AUS Eastern Standard Time)
new Date(482371200000)
Mon Apr 15 1985 10:00:00 GMT+1000 (AUS Eastern Standard Time)

So for some reason in Chrome, the one with Slashes is getting set to the timezone plus (what I assume is) my time offset. I know this isn't the answer but I couldn't post it all in the comment section sorry.

Upvotes: 1

Related Questions