Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript getTime() to 10 digits only

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.

like image 428
weyhei Avatar asked Nov 06 '12 00:11

weyhei


People also ask

What is new Date () getTime ()?

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).

What is 10 digit time?

It is the number of seconds since January 1st, 1970 at midnight GMT.

What does getTime return JavaScript?

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.

How to get current milliseconds in JavaScript?

The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.


3 Answers

I think you just have to divide it by 1000 milliseconds and you'll get time in seconds

Math.floor(date.getTime()/1000)
like image 142
Kirill Ivlev Avatar answered Oct 13 '22 09:10

Kirill Ivlev


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.

like image 31
RobG Avatar answered Oct 13 '22 09:10

RobG


Try dividing it by 1000, and use parseInt method.

const t = parseInt(Date.now()/1000);

console.log(t);
like image 25
Nayan Patel Avatar answered Oct 13 '22 09:10

Nayan Patel