呼......它看起來比它更容易了!
好的,這真的很棘手,因爲你必須考慮到JS客戶端偏移量。如果您將下一個代碼複製並粘貼到foo.php
中,並且您使用活動控制檯執行它,則會在控制檯中看到兩者(PHP和JS)相同。
你必須小心客戶端OFFSET的值(在我的情況下,UTC + 1,60分鐘),所以我糾正了我的PHP。您應該發送您使用的客戶端的OFFSET並使用它將其更正到服務器中,或者更好地說,服務器時間是您所在的時區以及數據與該時區相關的時間(由於您需要它可用無JS與客戶使用,這樣你就不會得到客戶端偏移)
<script>
// Creates a JavaScript Date instance that represents a single moment in time.
// Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.
// new Date(year, month [, day, hour, minute, second, millisecond]);
// REALLY TRICKY!! Month starts in 0!
var start = new Date(2014, 2, 1);
console.log('OFFSET (minutes): ' + start.getTimezoneOffset());
console.log('Date Start: ' + start.getTime());
console.log('Date NOW: ' + new Date().getTime());
var rate = 1/(30 * 1000);
console.log('Date substract: ' + (new Date() - start));
var amount = Math.floor((new Date() - start) * rate);
console.log('Amount: ' + amount);
</script>
<?php
// Returns the Unix timestamp corresponding to the arguments given.
// This timestamp is a long integer containing the number of seconds between the
// Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
// int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]])
// As month starts in 0 in js, here is month 3
$start = mktime(0, 0, 0, 3, 1, 2014);
echo 'Date Start MkTime: ' . $start . '<br>';
echo 'Date Start MkTime + JS OFFSET (-60 min * 60 sec): ' . ($start - 3600) . '<br>';
$start = $start - 3600;
echo 'Date Start: ' . $start . '<br>';
echo 'Date NOW: ' . time() . '<br>';
// You don't need divide between 1000 because PHP is seconds, in JS you get microsecs
$rate = 1/30;
echo 'Date substract: ' . (time() - $start) . '<br>';
$amount = floor((time() - $start) * $rate);
echo 'Amount: ' . $amount . '<br>';
在這裏,你有什麼我從我的瀏覽器中得到:
![enter image description here](https://i.stack.imgur.com/xnF85.png)
HTTP:// WWW .php.net/manual/en/class.datetime.php –