15

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.

weyhei
  • 479
  • 2
  • 7
  • 26
  • I am using a **WAMP** server(_development_) that's why the user and server time are the same. – weyhei Nov 06 '12 at 00:52

5 Answers5

41

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

Math.floor(date.getTime()/1000)
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
7

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
2

Try dividing it by 1000, and use parseInt method.

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

console.log(t);
Nayan Patel
  • 1,683
  • 25
  • 27
2
function ts() {
    return parseInt(Date.now()/1000);

}
dazzafact
  • 2,570
  • 3
  • 30
  • 49
0

You could divide by 1000 and use Math.floor() on JavaScript.

JCOC611
  • 19,111
  • 14
  • 69
  • 90