简体   繁体   中英

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

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.

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.

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

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

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

$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.

您可以将strtotime用于此目的:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM