- Add & Subtract Days Weeks Months To A Date In PHP
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- ADD & MINUS TO DATE
- 1) DATE TIME OBJECT
- 2) STRING TO TIME
- 3) UNIX TIMESTAMP
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- WHICH IS THE BEST?
- SUMMARY – ALL THE COMMON DATE/TIME FUNCTIONS
- INFOGRAPHIC CHEAT SHEET
- THE END
- Дата минус 1 год?
- Subtracting years from a date using PHP.
- Getting last year’s date using PHP’s strtotime and date functions.
- How to get last year’s date using DateTime.
- Subtracting years from a given date using the strtotime and date functions.
- Using DateTime to subtract years from a given date.
- Do not attempt to subtract the year(s) using basic math.
- Ten years ago.
Add & Subtract Days Weeks Months To A Date In PHP
Welcome to a quick tutorial on how to add and subtract days, weeks, months to a date in PHP. So you need to do some “date yoga” in your project?
- Create a date-time object, then use the modify function.
- $dt = new DateTime(«2019-08-14»);
- $dt->modify(«+4 days»);
- $dt->modify(«-1 week»);
- Use the strtotime() function.
- $date = «2019-08-14»;
- $add = date(«d M Y», strtotime($date . «+1 week»));
- minus = date(«d M Y», strtotime($date . «-2 months»));
- Manually calculate using the Unix timestamp.
- $unix = strtotime(«2019-08-14»);
- $add = date(«d M Y», $unix + (2*86400));
- $minus = date(«d M Y», $unix — (14*86400));
That covers the basics, but let us walk through more examples in this guide – Read on!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
ADD & MINUS TO DATE
All right, let us now get into the examples of how to add/minus days, weeks, months to a date in PHP.
1) DATE TIME OBJECT
format("d M Y") . "
"; // (B) ADD DAYS WEEKS MONTHS $dt->modify("+4 days"); echo "+4 DAYS: " . $dt->format("d M Y") . "
"; $dt->modify("+2 weeks"); echo "+2 WEEKS: " . $dt->format("d M Y") . "
"; $dt->modify("+1 month"); echo "+1 MONTH: " . $dt->format("d M Y") . "
"; // (C) SUBTRACT DAYS WEEKS MONTHS $dt->modify("-2 days"); echo "-2 DAYS: " . $dt->format("d M Y") . "
"; $dt->modify("-1 week"); echo "-1 WEEK: " . $dt->format("d M Y") . "
"; $dt->modify("-2 months"); echo "-2 MONTHS: " . $dt->format("d M Y") . "
";
This should be self-explanatory. The new DateTime(TIMESTAMP) object is probably one of the most painless and “human” ways to manipulate a given date. Simply use the format() function to add or subtract a range of days, weeks, months, years from the timestamp.
2) STRING TO TIME
"; // (B) ADD DAYS WEEKS MONTHS $added = date("d M Y", strtotime($date . "+4 days")); echo "+4 DAYS: $added
"; $added = date("d M Y", strtotime($date . "+2 weeks")); echo "+2 WEEKS: $added
"; $added = date("d M Y", strtotime($date . "+1 month")); echo "+1 MONTH: $added
"; // (C) SUBTRACT DAYS WEEKS MONTHS $added = date("d M Y", strtotime($date . "-4 days")); echo "-4 DAYS: $added
"; $added = date("d M Y", strtotime($date . "-2 weeks")); echo "-2 WEEKS: $added
"; $added = date("d M Y", strtotime($date . "-1 month")); echo "-1 MONTH: $added
";
Yep, another simple one. This is actually a combination of using the strtotime() function to add/subtract the date, then using date() to get the date format that you want. I will leave links in the summary below on how date() works.
3) UNIX TIMESTAMP
"; echo "+2 WEEKS: " . date("d M Y", $unix + (14*$day)) . "
"; // BE CAREFUL: 1 MONTH MAY NOT BE EXACTLY 30 DAYS echo "+1 MONTH: " . date("d M Y", $unix + (30*$day)) . "
"; // (C) SUBTRACT DAYS WEEKS MONTHS echo "-3 DAYS: " . date("d M Y", $unix - (3*$day)) . "
"; echo "-2 WEEKS: " . date("d M Y", $unix - (14*$day)) . "
"; echo "-1 MONTH: " . date("d M Y", $unix - (30*$day)) . "
";
Lastly, for you guys who do not know – strtotime(TIMESTAMP) actually returns a Unix timestamp. That is, the number of seconds that have elapsed since 1 Jan 1970 UTC. So to add and subtract days/weeks/months with the Unix Timestamp is a very Mathematical process.
- Essentially, one day has 24 hours (or 86400 seconds).
- So for example, if we want to add 3 days to a timestamp, that will be $unix += 3 * 86400 ;
- Another example, if we want to add 2 weeks, that will be 14 days – $unix += 14 * 86400 .
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this tutorial, and here is a small section on some extras that may be useful to you.
WHICH IS THE BEST?
Personally, I am leaning toward DateTime and strtotime for convenience. But the performance of these 2 is not exactly amazing… Manually calculating with the Unix timestamp is not all bad, and it has an edge when it comes to processing in a loop – for ($i=1; i
SUMMARY – ALL THE COMMON DATE/TIME FUNCTIONS
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to understand better, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Дата минус 1 год?
Функция strtotime возвращает strtotime метку unix, для получения форматированной строки вы можете использовать date :
echo date('Ym-d', $date); // echoes '2009-01-01'
Используйте функцию strtotime ():
$time = strtotime("-1 year", time()); $date = date("Ymd", $time);
Использование объекта DateTime …
$time = new DateTime('2099-01-01'); $newtime = $time->modify('-1 year')->format('Ym-d');
Или использовать сейчас на сегодня
$time = new DateTime('now'); $newtime = $time->modify('-1 year')->format('Ym-d');
самый простой способ, которым я пользовался и работал хорошо
это сработало отлично .. надеюсь, это поможет кому-то еще .. 🙂
// set your date here $mydate = "2009-01-01"; /* strtotime accepts two parameters. The first parameter tells what it should compute. The second parameter defines what source date it should use. */ $lastyear = strtotime("-1 year", strtotime($mydate)); // format and display the computed date echo date("Ymd", $lastyear);
Вы можете использовать следующую функцию для вычитания 1 или любых лет с даты.
function yearstodate($years) < $now = date("Ymd"); $now = explode('-', $now); $year = $now[0]; $month = $now[1]; $day = $now[2]; $converted_year = $year - $years; echo $now = $converted_year."-".$month."-".$day; >$number_to_subtract = "1"; echo yearstodate($number_to_subtract);
И, глядя выше, вы также можете использовать следующие
$user_age_min = "-"."1"; echo date('Ym-d', strtotime($user_age_min.'year'));
Subtracting years from a date using PHP.
In this tutorial, we will show you how to subtract years from a date using PHP.
We will also provide you with tips on how to avoid running into issues with leap years.
Getting last year’s date using PHP’s strtotime and date functions.
To get last year’s date using the strtotime and date functions, you can use the following code:
//Get last year's date in a YYYY-MM-DD format. $lastYear = date("Y-m-d", strtotime("-1 years")); //On 2019-08-22, this resulted in 2018-08-22. var_dump($lastYear);
In the example above, we passed in “-1 years” as a parameter to strtotime.
Essentially, this tells the strtotime function to subtract one year from the current Unix timestamp.
Passing in “-12 months” will also accomplish the exact same thing:
//You can also get last year's date using -12 months. $twelveMonthsAgo = date("Y-m-d", strtotime("-12 months")); //Also resulted in 2018-08-22. var_dump($twelveMonthsAgo);
Both of these examples will return last year’s date in a YYYY-MM-DD format.
How to get last year’s date using DateTime.
If you’re using PHP version 5.3.0 or above and you want to use an object-oriented approach, then you can use the DateTime and DateInterval objects.
In the following example, we subtract one year from today’s date:
//Current Date & Time. $currentDate = new DateTime(); //Get last year's date using the //DateTime::sub function and DateInterval $lastYearDT = $currentDate->sub(new DateInterval('P1Y')); //Get last year's date string in a YYYY-MM-DD format. $lastYear = $lastYearDT->format('Y-m-d'); //var_dump the result. var_dump($lastYear);
- We created a new DateTime object representing today’s date.
- We used the DateTime::sub function to subtract a DateInterval object of P1Y year from the current year. The P1Y $interval_spec parameter means “a period of 1 year.” If we wanted to subtract 2 years instead of 1, we can change “P1Y” to “P2Y”.
- Finally, we got the date in a YYYY-MM-DD format and printed it out onto the page.
Subtracting years from a given date using the strtotime and date functions.
If there is a specific date that you need to subtract a year from, then you can use the following code snippet:
//Minus one year from a given date. $date = '2019-09-09'; $dateMinusOneYear = date("Y-m-d", strtotime("-1 year", strtotime($date))); //Results in 2018-09-09. var_dump($dateMinusOneYear);
In the example above, we passed in a Unix timestamp representation of our date as the 2nd parameter to strtotime.
Using DateTime to subtract years from a given date.
You can also use the DateTime object to subtract years from a given date:
//New DateTime object with a given date. $dt = new DateTime('2016-02-29'); //Subtract one year. $minusOneYearDT = $dt->sub(new DateInterval('P1Y')); //Get it in a YYYY-MM-DD format. $minusOneYear = $minusOneYearDT->format('Y-m-d'); //var_dump the result - 2015-03-01 var_dump($minusOneYear);
The only real difference between this example and the first DateTime example is that we passed the date in question in as the $time parameter in the constructor.
If you run the code snippet above, you will see it prints out “2015-03-01” instead of “2015-02-29”.
This is because 2015 was not a leap year. As a result, it didn’t have 29 days in February.
In other words, February 29th, 2015 never occurred.
This leads us to our next point.
Do not attempt to subtract the year(s) using basic math.
Here are two bad examples of subtracting a year from a date:
$lastYear = date("Y") - 1; $lastYearDate = date($lastYear . "-m-d"); var_dump($lastYearDate);
The solution above will fail if the current date is February 29th in a leap year.
Here is another bad example:
//Another bad example. $dateString = '2016-02-29'; $exploded = explode("-", $dateString); $lastYear = ($exploded[0] - 1) . "-" . $exploded[1] . "-" . $exploded[2]; //Results in 2015-02-29 var_dump($lastYear);
In the code above, we exploded the date, subtracted one year, and then put the date back together again.
Although this approach seems simple and straight-forward, it also fails to adequately deal with leap years. The above example prints out “2015-02-29”, which is an invalid date.
Ten years ago.
In this example, we will subtract 10 years from today’s date:
//Get 10 years ago in a YYYY-MM-DD format. $tenYearsAgo = date("Y-m-d", strtotime("-10 years")); //On 2019-08-22, this resulted in 2009-08-22. var_dump($tenYearsAgo);
We can also achieve the same result using the DateTime object:
//Current Date & Time. $currentDate = new DateTime(); //Get 10 years ago. $tenYearsAgoDT = $currentDate->sub(new DateInterval('P10Y')); //YYYY-MM-DD format. $tenYearsAgo = $tenYearsAgoDT->format('Y-m-d'); //var_dump the result. var_dump($tenYearsAgo);
Here, we passed in P10Y as the $interval_spec parameter for DateInterval.
Other periods that you can use as the $interval_spec parameter include:
- P3Y: To subtract 3 years.
- P5Y: To subtract 5 years.
- P20Y: To subtract 20 years.
- P50Y: To subtract 50 years.