Javascript Date() give wrong date off by one hour

后端 未结 4 828
迷失自我
迷失自我 2020-12-03 21:33

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

@Temporal(TemporalType.TIMESTAM         


        
4条回答
  •  鱼传尺愫
    2020-12-03 22:08

    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.

提交回复
热议问题