如何从今天的日期(PHP)计算并获取过去(例如 3 周前)的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4575364/
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 13:31:59  来源:igfitidea点击:

How to calculate and get a date in the past (e.g. 3 weeks ago) from today's date (PHP)

phpdate

提问by Ahmad Fouad

I have a news filtering script and I use this usually to get the current day:

我有一个新闻过滤脚本,我通常使用它来获取当前日期:

echo date('j n Y');

Which returns something like 1 1 2011. What I want to do is being able to return the date a week ago relative to current date/day so that it would return just example (25 12 2010) if I choose to get 1 week ago. And so on if I want to get the day and month and year 3 weeks ago relative to current day.

它返回类似 1 1 2011 的内容。我想要做的是能够返回一周前相对于当前日期/天的日期,以便如果我选择获取 1 周前,它只会返回示例 (25 12 2010)。依此类推,如果我想获得 3 周前相对于当天的日期、月份和年份。

I do not know is that possible? given that I only have to use the current day month and year to retrieve past date, and I should be able to retrieve the past date as day, month, and year to use in the script.

我不知道这可能吗?鉴于我只需要使用当前的月份和年份来检索过去的日期,并且我应该能够将过去的日期检索为要在脚本中使用的日、月和年。

If my question is not clear, please let me know. I apologize.

如果我的问题不清楚,请告诉我。我道歉。

回答by NickAldwin

strtotimewill give you a past date in unix time, which you can then feed into the date function:

strtotime将为您提供 unix 时间的过去日期,然后您可以将其输入到 date 函数中:

echo date('j n Y', strtotime("-3 weeks"))

回答by Maerlyn

Use the DateTime class instead of timestamp. With php 5.2 and above:

使用 DateTime 类而不是时间戳。使用 php 5.2 及更高版本:

$date = new DateTime(); //defaults to the current date/time
echo $date->modify("-3 week")->format("Y-m-d");

This class can also handle dates before 1970 and after 2038.

此类还可以处理 1970 年之前和 2038 年之后的日期。

回答by Simon

you can use strtotime for that purpose:

您可以为此目的使用 strtotime:

echo date('j n Y',strtotime('-1 week'))