Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date() give wrong date off by one hour

Tags:

I send this date from my controller in java (Spring-MVC) the type in mysql is datetime

@Temporal(TemporalType.TIMESTAMP)  @Column(name = "..") public Date getYy() {      return this.yy;  } 

as : [2015-09-30 00:00:00.0]

When i get this dates with ajax as 1443567600000 :

new Date(1443567600000) convert to Tue Sep 29 2015 23:00:00 GMT+0000 (Maroc)

So why i get wrong date off by one hour?

SOLUTION

We resolve it by

d = new Date(value) ; d.setTime( d.getTime() - new Date().getTimezoneOffset()*60*1000 ); 

because it was Daylight saving time (DST) or summer time problem. good article

like image 457
Hayi Avatar asked Sep 09 '15 00:09

Hayi


1 Answers

This JS handling of Date is a quite a head-flip.

I'm in the UK... "easy" because we're on GMT (UTC)... except during the summer months, when there's DST (British Summer Time, BST). Clocks go forward in summer and back in winter (stupidly by the way, but that's another issue!) by one hour. One day in March what is 4pm GMT is now called 5pm (BST).

summer month:

If you do new Date( '2017-08-08' ) this will give you (toString) 'Date 2017-08-08T00:00:00.000Z'.

If you do new Date( '2017-08-08 00:00' ), however, this will give you 'Date 2017-08-07T23:00:00.000Z'!

In the second case it appears JS is trying to be "helpful" by assuming that because you stipulated the hour you were specifying BST time. So it adjusts to GMT/UTC. Otherwise it doesn't... though (of course) it still produces a Date object which is specific right down to the milliseconds. Quite a gotcha!

Confirmation: a winter month... when BST is not applied: new Date( '2018-01-01 00:00' )/ new Date( '2018-01-01' ): both give 'Date 2018-01-01T00:00:00.000Z'

As for adjusting, it appears that to undo the automatic adjustment you just go

jsDate.setTime( jsDate.getTime() + jsDate.getTimezoneOffset() * 60 * 1000 ); 

... this is a bit like what Youssef has written... except you have to obtain the offset from the specific Date in question... and my experiments seem to prove that you add this, not subtract it.

Really it would be much more helpful if the default string representation of JS Date gave the UTC time followed by the TZ (time zone) offset information, as with some of the ISO date formats: clearly, this information is included.

like image 151
mike rodent Avatar answered Sep 20 '22 18:09

mike rodent