I am using 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 is:
1352162391299
While in PHP, I use the time();
function to get Time and the value I get is
1352162391
How do I convert the value of javascript time to remove the last 3 digits and make it 10 digits only.
From 1352162391299
To 1352162391
So that the Javascript time is the same with the PHP time.
The date. getTime() method is used to return the number of milliseconds since 1 January 1970. when a new Date object is created it stores the date and time data when it is created. When the getTime() method is called on this date object it returns the number of milliseconds since 1 January 1970 (Unix Epoch).
It is the number of seconds since January 1st, 1970 at midnight GMT.
The getTime() method returns the number of milliseconds since the ECMAScript epoch. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.
The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
I think you just have to divide it by 1000 milliseconds and you'll get time in seconds
Math.floor(date.getTime()/1000)
If brevity is ok, then:
function secondsSinceEpoch() {
return new Date/1000 | 0;
}
Where:
new Date
is equivalent to new Date()
| 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 newer features, and allowing for a Date to be passed to the function, the code can be reduced to:
let getSecondsSinceEpoch = (x = new Date) => x/1000 | 0;
But I prefer function declarations as I think they're clearer.
Try dividing it by 1000, and use parseInt method.
const t = parseInt(Date.now()/1000);
console.log(t);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With