简体   繁体   中英

Convert Javascript Date() to PHP Unix timestamp

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 eg 1 day ago, 2 days ago...

您是否在javascript上尝试过此功能?

Math.floor(Date.now() / 1000);
$date = (int) substr($date, 0, strlen($date) - 3);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM