在 PHP 中如何获取一周前的时间戳?

40

我需要使用PHP计算七天前的时间戳,例如现在是3月25日晚上7点30分,它应该返回3月18日晚上7点30分的时间戳。

我只需从当前时间戳减去604800秒,或者有更好的方法吗?

6个回答

88
strtotime("-1 week")

27

strtotime 是你的好朋友

echo strtotime("-1 week");

1
你打错了strotime,应该是strtotime.. :) 太早了,只有5年前.. .:D - Sanjay

11

9
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";
?>

将第一行(或最后一行)的+更改为-即可获得您想要的结果。

4
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

不要使用字符串创建DateTime,你可以在对象上直接setTimestamp

$timestamp=1427241600;//2015-03-25
$datetime=new DateTime();
$datetime->setTimestamp($timestamp);
$datetime->modify('-7 day');
echo $datetime->format("Y-m-d"); //2015-03-18

0
<?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);

1
@AndrewBarber 这个答案可能已经被编辑过了,但是它似乎没有包含任何链接。 - starbeamrainbowlabs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接