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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2507678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:44:35  来源:igfitidea点击:

Get the timestamp of exactly one week ago in PHP?

phpdatetimetimestamp

提问by Mike Crittenden

I need to calculate the timestamp of exactly 7 days ago using PHP, so if it's currently March 25th at 7:30pm, it would return the timestamp for March 18th at 7:30pm.

我需要使用 PHP 计算恰好 7 天前的时间戳,因此如果当前是 3 月 25 日晚上 7:30,它将返回 3 月 18 日晚上 7:30 的时间戳。

Should I just subtract 604800 seconds from the current timestamp, or is there a better method?

我应该从当前时间戳中减去 604800 秒,还是有更好的方法?

回答by SilentGhost

strtotime("-1 week")

回答by Ben Everard

strtotimeis your friend

strtotime是你的朋友

echo strtotime("-1 week");

回答by Aaron W.

回答by Luís Guilherme

There is the following example on PHP.net

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

Changing + to - on the first (or last) line will get what you want.

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

回答by Pawe? Tomkiel

From PHP 5.2you can use DateTime:

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

Instead of creating DateTimewith string, you can setTimestampdirectly on object:

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

回答by Navdeep Singh

<?php 
   $before_seven_day = $date_timestamp - (7 * 24 * 60 * 60)
   // $date_timestamp is the date from where you found to find out the timestamp.
?>

you can also use the string to time function for converting the date to timestamp. like

您还可以使用 string to time 函数将日期转换为时间戳。喜欢

strtotime(23-09-2013);