如何将php中的strtotime转换为js中的new Date

how to convert strtotime in php to new Date in js

本文关键字:中的 js new Date 转换 strtotime php      更新时间:2023-09-26

对于实时倒计时,我使用一些php变量并在js中回显它们,如下所示:

$expire_year = '2016';  // year
$expire_month = '8'; // month ( 8 = August)
$expire_day = '14'; // day (14th)
$expire_hour = '2'; // hour ( 1-24)
$expire_minutes = '12'; // minutes 

我在js中使用它们,如blow:

timestamp = new Date(<?php echo $expire_year; ?>, <?php echo $expire_month - 1; ?>, <?php echo $expire_day; ?>, <?php echo $expire_hour; ?>, <?php echo $expire_minutes; ?>),

这个工作很好!

我使用php strtotime来检查日期是否真的过期了:

 $quickpollexpiredate = strtotime("August 14, 2016 2:12"); // set an expiration date

所以对于js中的倒计时计时器和php中的检查,我必须使用2个不同的日期"结构"。

是否可以在php中进行检查,以便我只能使用5个变量($expire_year, $expire_month…)与strtotime()或其他函数?

所以实际上我想要实现的是这样的东西(当然这是错误的,但我希望你理解我想要实现的)

$quickpollexpiredate = strtotime($expire_year, $expire_month, $expire_day, $expire_hour, $expire_minutes); // set an expiration date

如果你在php中有一个时间戳,你可以很容易地使用它来设置javascript中的Date对象。你只需要考虑javascript中的时间戳是以毫秒为单位,而不是像php中的那样以秒为单位:

jsTimestamp = new Date(<?php echo $phpTimestamp; ?> * 1000);

jsTimestamp = new Date(<?php echo strtotime($yourDateString); ?> * 1000);

注意new Date(...)也接受字符串,详见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date