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

1
  • 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? Commented Dec 29, 2015 at 20:33

3 Answers 3

6

Did you try this on javascript ?

Math.floor(Date.now() / 1000);
Sign up to request clarification or add additional context in comments.

2 Comments

I want to use php. The $date is returned from an external source in which they use js
Ok, did you try the same in php ? floor($jsDate / 1000)
2
$date = (int) substr($date, 0, strlen($date) - 3);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.