Home > Net >  JavaScript returns incorrect date value after using setHours()
JavaScript returns incorrect date value after using setHours()

Time:12-02

This is pretty self explanatory if you compare the two date values that are returned. If the second value is also a date, but for some reason printed in a strange way, can I somehow convert it to similar format to the first value, so I know that the time is set correctly?

const date = new Date()
console.log(date)
console.log(date.setHours(5))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

var date = new Date()
console.log(date)
date = new Date(date.setHours(5))
console.log(date)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

First you have to set the hour then you can log the date with correct format. Because setHours() is a function that returns the number of milliseconds and the updated date. The default date will be formatted according to universal” UTC time. IST will be 6hrs behind hence if you will setHours(12) then it will be 6pm in IST and if you will setHours(n) then it will be n 6 in 24hrs format.

let date = new Date()
console.log(date)
date.setHours(5)
console.log(date)

//OR

date = new Date(date.setHours(5))
console.log(date)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related