Javascript getTime () up to 10 digits

I use the following function to get the time using javascript:

function timeMil(){ var date = new Date(); var timeMil = date.getTime(); return timeMil; } 

And the value I get:

1352162391299

In PHP, I use the time(); function time(); to get the time, and the value that I get,

 1352162391 

How do I convert the javascript time value to remove the last 3 digits and make only 10 digits.

From 1352162391299
K 1352162391
So Javascript time is the same as PHP time.

+5
source share
4 answers

I think you just need to divide it by 1000 milliseconds and you will get time in seconds

 Math.floor(date.getTime()/1000) 
+17
source

If brevity is in order, then:

 function secondsSinceEpoch() { return new Date/1000 | 0; } 

Where:

  • new Date equivalent to new Date()
  • | 0 | 0 truncates the decimal part of the result and is equivalent to Math.floor(new Date/1000) (see What does | 0 do in javascript ).

Using new functions and allowing you to pass the date to a function, the code can be reduced to:

 let getSecondsSinceEpoch = (x = new Date) => x/1000 | 0; 

But I prefer function declarations, because I think they are clearer.

+4
source

You can divide by 1000 and use Math.floor() for JavaScript.

0
source

Try dividing it by 1000 and use the parseInt method.

 const t = parseInt(Date.now()/1000); console.log(t); 
0
source

Source: https://habr.com/ru/post/1444234/


All Articles