2

Hi this is incredibly simple i cant believe im asking this.

I have tried the following:

Moment.now()
Date.now()
new Date().valueOf()

And various other tricks found in other stack overflow questions

They all give me the time in microseconds.

e.g

1543409290654

which is 09/10/50878 @ 10:57am (UTC)

Im aware i could divide by 1000 but surely there is an api in javascript to get the unix timestamp in milliseconds.

Ive have seen this in chrome and react native

EDIT:

So i realise my stupidity i was putting the unix timestamp into a website that renders it as an ISO date but it was expecting seconds which is why i thought my dates were coming in as milliseconds

Luke De Feo
  • 2,025
  • 3
  • 22
  • 40
  • 1
    What is the desired output you are looking for? and what are you actually getting? – Ahmad Nov 28 '18 at 12:56
  • 1
    Possible duplicate of [Getting current unixtimestamp using Moment.js](https://stackoverflow.com/questions/25499191/getting-current-unixtimestamp-using-moment-js) – Hassan Imam Nov 28 '18 at 12:57
  • 2
    `Im aware i could divide by 1000` There is your answer, are you having trouble dividing by 1000?. – Keith Nov 28 '18 at 12:58
  • console.log(Date.now()) returns 1543409203060 this is not a unix millisconds timestamp. its microseconds – Luke De Feo Nov 28 '18 at 13:02
  • `ITS NOT working, please read my question` I think everyone appears to have read the question, but you seem to be ignoring them. Your still not dividing by 1000, and wonder why it's wrong. `(new Date().getTime() / 1000 | 0)` ps. Avoid ITS NOT working, it's not helpful. – Keith Nov 28 '18 at 13:06
  • As others have pointed out the docs say these apis should return a unix timestamp in milliseconds. How is dividing by 1000 solution. Obviously something else is wrong – Luke De Feo Nov 28 '18 at 13:08
  • Because the unix time your after is in seconds, not milliseconds. AKA, why you want to divide by 1000. – Keith Nov 28 '18 at 13:17

2 Answers2

15

Date.now() returns the number of milliseconds since midnight January 1, 1970

lostbard
  • 5,065
  • 1
  • 15
  • 17
  • If i go into the console and do console.log(Date.now()) i get 1543409203060 this is not milliseconds since epoch – Luke De Feo Nov 28 '18 at 13:03
  • in unix the number of seconds since 1Jan 1970 is 1543410557 (as of this moment), so that looks like milliseconds to me. microseconds=1 millionth of a second, milliseconds being 1 thousandth of a second. so 3 digits more than the seconds value. – lostbard Nov 28 '18 at 13:11
  • ok Im dumb i was putting the timestamp into a website to render it and that was causing the confusion. Thanks – Luke De Feo Nov 28 '18 at 13:17
11

There is no native javascript to format time into unix-timestamp.

I found this useful

var today = Math.round((new Date()).getTime() / 1000);

console.log(today);
Ahmad
  • 12,336
  • 6
  • 48
  • 88