PHP中是否存在以下JavaScript代码?
我希望用PHP回显金额,以便每当访问者禁用JavaScript时,该金额仍可在页面上显示。
我对PHP不太好,所以如果有人能帮助我或指出正确的方向,我将不胜感激。
的JavaScript
var start = new Date(2014, 2, 1);
var rate = 1 / (30 * 1000);
var amount = Math.floor((new Date() - start) * rate);
答案 0 :(得分:2)
试试这个:
$start = mktime(0, 0, 0, 2014, 2, 1);
$rate = 1 / (30 * 1000);
$amount = ((time() - $start) * $rate) | 0;
答案 1 :(得分:2)
Phew ......它看起来比它更容易!
好的,这真的很棘手,因为你必须考虑到JS客户端的偏移。如果将下一个代码复制并粘贴到foo.php
中并使用活动控制台执行它,您将看到控制台中的两个(PHP和JS)是相同的。
您必须小心客户端OFFSET的值(在我的情况下,UTC + 1,60分钟),所以我在PHP中更正了。您应该发送您使用的客户端的OFFSET并使用它来将其更正到服务器中,或者更好,说服务器时间是您所在的时区以及数据与该时区相关(由于您需要它)在没有JS可用的客户端使用它,所以你不会得到客户端Offset)
<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>';
这里有我从浏览器中获得的内容:
答案 2 :(得分:1)
<?php
$start = strtotime("2011-02-01");
$rate = 1 / (30 * 1000);
$amount = floor((time() - $start) * $rate);
echo $amount;
?>