Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct a UTC date in Javascript as an object, not a number?

In Javascript, given d=new Date() it might be the case that d.getHours()!=d.getUtcHours().

I can construct a Date object, giving the components explicitly

new Date (y, m, d, hrs, mins)

but if these components are UTC then I have a problem. From the docs

The UTC() method differs from the Date constructor in two ways.

  • Date.UTC() uses universal time instead of the local time.

  • Date.UTC() returns a time value as a number instead of creating a Date object.

How do I construct a Date object given UTC components?

like image 905
spraff Avatar asked Dec 08 '25 04:12

spraff


2 Answers

according to this answer you can do it like this:

new Date(Date.UTC(year, month, day, hour, minute, second))

like image 103
pwolaq Avatar answered Dec 10 '25 17:12

pwolaq


How about new Date(Date.UTC(...)), e.g. new Date(Date.UTC(2016, 9, 5, 13, 11, 5)).

like image 23
tros443 Avatar answered Dec 10 '25 16:12

tros443



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!