date.setHours() not working

后端 未结 5 365
一生所求
一生所求 2021-01-19 08:17

I am trying to subtract hours from a given date time string using javascript. My code is like:

     var cbTime = new Date();    
     cbTime = selectedTime.s         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 09:18

    Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.

    Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).

    You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.

提交回复
热议问题