简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM