【发布时间】:2011-01-31 05:59:26
【问题描述】:
我需要使用 PHP 计算 7 天前的时间戳,所以如果当前是 3 月 25 日晚上 7:30,它将返回 3 月 18 日晚上 7:30 的时间戳。
我应该从当前时间戳中减去 604800 秒,还是有更好的方法?
【问题讨论】:
我需要使用 PHP 计算 7 天前的时间戳,所以如果当前是 3 月 25 日晚上 7:30,它将返回 3 月 18 日晚上 7:30 的时间戳。
我应该从当前时间戳中减去 604800 秒,还是有更好的方法?
【问题讨论】:
strtotime("-1 week")
【讨论】:
strtotime是你的朋友
echo strtotime("-1 week");
【讨论】:
echo strtotime("-1 week");
【讨论】:
PHP.net上有如下例子
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
将第一行(或最后一行)的 + 更改为 - 将得到您想要的。
【讨论】:
<?php
$before_seven_day = $date_timestamp - (7 * 24 * 60 * 60)
// $date_timestamp is the date from where you found to find out the timestamp.
?>
您还可以使用字符串到时间函数将日期转换为时间戳。喜欢
strtotime(23-09-2013);
【讨论】:
从 PHP 5.2 开始,您可以使用 DateTime:
$timestring="2015-03-25";
$datetime=new DateTime($timestring);
$datetime->modify('-7 day');
echo $datetime->format("Y-m-d"); //2015-03-18
您可以直接在对象上setTimestamp,而不是使用字符串创建DateTime:
$timestamp=1427241600;//2015-03-25
$datetime=new DateTime();
$datetime->setTimestamp($timestamp);
$datetime->modify('-7 day');
echo $datetime->format("Y-m-d"); //2015-03-18
【讨论】: