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.