如何将 php 时间戳与 jquery 进行比较

时间:2021-01-11 20:29:44

标签: javascript php jquery

我有:

$_SESSION['CREATED'] = time(); 

在 php 中。

我正在尝试将它“注入”到 jquery:

var sesstime = <?php echo json_encode($_SESSION['CREATED']) ?>;

现在我想要当前日期:

var timestampjq = (new Date()).getTime();

以及如何格式化这些日期?

我想使用:

if(timestampjq - sesstime > 60) {

}

还是胡说八道?

3 个答案:

答案 0 :(得分:1)

JS - getTime()

The getTime() method returns the number of milliseconds* since the Unix Epoch.

JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.

getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime

PHP - time()

<块引用>

返回以秒为单位测量的当前时间 Unix 纪元(1970 年 1 月 1 日 00:00:00 GMT)。

https://www.php.net/manual/en/function.time.php

计算

所以基本上,你可以做那个计算,只要记住 JS 以毫秒为单位,PHP 时间以秒为单位,所以只需将 php 的值乘以 1000。

if(timestampjq - sesstime*1000 > 60) {

重要通知:服务器时间和浏览器时间可能存在差异。

答案 1 :(得分:1)

来自 PHP 文档:

<块引用>

[time()] 返回自 Unix 纪元以来以 为单位测量的当前时间

来自 getTime 的 MDN 文档:

<块引用>

JavaScript 使用毫秒作为度量单位,而 Unix 时间以秒为单位。

答案 2 :(得分:1)

您可以使用 PHP 的 microtime 函数作为 UNIX 日期。PHP 的 TimeStamp 以微秒为单位返回。

Javascript getTime() 函数以毫秒为单位返回 UNIX 日期。

然后,如果您想使用它,则需要将“000”添加到您的 PHP 时间戳中,例如:

$yourPHPTimeStamp= round(microtime(true) * 1000);

无论如何我都会帮助你;)

相关问题