1

I am recieving a date which uses javascript's date() function to generate a timestamp like so.

1451351941210

However my application is in php and I would like to convert that value to a unix timestamp like below

1451419198

I have tried dividing by 1000 but the function comes back as 18 years not 18 seconds.

Here is the code below

<?php

// Get javascript date() value
$date = 1451351941210;

// divide by 100 and round
$start_time = round($date/1000);

// run through function and echo
echo time_elapsed_string('@'. $start_time);

// Time function
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

Is there anything to directly convert the date() to a unix timestamp?

I want to use PHP, not javascript

The function I have used is taken from

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

Community
  • 1
  • 1
ServerSideSkittles
  • 2,713
  • 10
  • 34
  • 60
  • You have a strange output from Javascript. It is quite distant from what I get now: 1451421138877. Could you show the exact JS code how you got it? – trincot Dec 29 '15 at 20:33

3 Answers3

6

Did you try this on javascript ?

Math.floor(Date.now() / 1000);
abeyaz
  • 3,034
  • 1
  • 16
  • 20
2
$date = (int) substr($date, 0, strlen($date) - 3);
Deep
  • 2,472
  • 2
  • 15
  • 25
2

To convert the current date and time to a UNIX timestamp do the following:

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

getTime() returns milliseconds from the UNIX epoch, so divide it by 1000 to get the seconds representation. It is rounded using Math.round() to make it a whole number. The "ts" variable now has the UNIX timestamp for the current date and time relevent to the user's web browser.

MistaJase
  • 839
  • 7
  • 12