2

I know how to change new Date() to UTC time by doing new Date().toUTCString() But I want to take it a step further by getting the UTC time and THEN changing it into milliseconds since Jan. 1, 1970.

I tried

new Date().toUTCString().getTime()

but it says that .getTime() is not a function for the date after it is converted to UTC time. Is there any real solution?

  • For any serious time/date manipulation in JS you should have a look at [moment.js](https://momentjs.com/). – Stefan Becker Aug 02 '19 at 04:25
  • `toUTCString()` returns a *string* not a Date, hence why you can't call `getTime` on it. Considering that date would be equivalent to the Unix timestamp from `getDate`, I don't understand what are you trying to achieve. – VLAZ Aug 02 '19 at 04:25

3 Answers3

0

why not just new Date().getTime()? the .toUTCString will make it non Date object. so the getTime() will not work

wakakak
  • 842
  • 5
  • 13
0

I think you are running getTime() method on string resulted from new Date().toUTCString().

Try to use : new Date(new Date().toUTCString()).getTime()

shyamzzp
  • 115
  • 7
  • This does return an integer of milliseconds, but oddly it still returns milliseconds since Jan. 1, 1970 for my local time(EST). I am wanting to receive milliseconds since Jan. 1, 1970 for UTC time. Unbiased as to which timezone I am in, or (which timezone client side browser is in) – riptidebongolio Aug 02 '19 at 05:01
0

The Date object already is in "milliseconds since epoch", which is in UTC. So you just need to prevent string conversion. F.ex. using Node.js on my Linux machine I get:

$ node
> new Date() * 1
1564721436203
> 

# cutting off the ...203 milliseconds
$ LC_ALL=C date --date @1564721436 --utc
Fri Aug  2 04:50:36 UTC 2019

But for any serious date/time manipulation in JS I would recommend Moment.js.

Stefan Becker
  • 5,695
  • 9
  • 20
  • 30
  • "But for any serious date/time manipulation in JS I would recommend Moment.js." Libraries come and go and Momentjs is not maintained any more. – Daniel May 18 '22 at 10:26