Php date minus month

PHP: Subtract days from a date.

In this tutorial, we will show you how to subtract days, weeks, or months from a date using PHP.

To do this, we can use the strtotime function or the DateTime object.

How to subtract one day from a date using PHP.

To get yesterday’s date, you can pass in the string “yesterday” to the strtotime function like so:

//Yesterday $yesterday = date("Y-m-d", strtotime("yesterday")); //On 2019-08-19, this resulted in 2019-08-18 echo $yesterday;

Passing in the string “yesterday” to strtotime is basically the exact same thing as subtracting “-1 day” from today’s date.

Here is a DateTime alternative, which you can use if your PHP version is 5.3.0 or above:

//New DateTime object representing today's date. $currentDate = new DateTime(); //Use the sub function to subtract a DateInterval $yesterdayDT = $currentDate->sub(new DateInterval('P1D')); //Get yesterday's date in a YYYY-MM-DD format. $yesterday = $yesterdayDT->format('Y-m-d'); //Print it out. echo $yesterday;

PHP introduced the DateInterval object in version 5.3.0. This object represents a date interval.

Читайте также:  Read excel file in python pandas

In the example above, we set the DateInterval object to P1D, which means a period of one day. We then subtracted that interval from the current date.

If you would like to subtract five days instead of one day, then you can use P5D instead of P1D.

If you want to subtract a day from a given date:

//Pass the date you want to subtract from in as //the $time parameter for DateTime. $currentDate = new DateTime('2019-01-01'); //Subtract a day using DateInterval $yesterdayDT = $currentDate->sub(new DateInterval('P1D')); //Get the date in a YYYY-MM-DD format. $yesterday = $yesterdayDT->format('Y-m-d'); //Print it out. echo $yesterday;

In the example above, we subtracted one day from 2019-01-01. This resulted in “2018-12-31”.

Subtract 7 days.

To get last week’s date in PHP, we can use the strtotime function like so:

//7 days ago - last week. $lastWeek = date("Y-m-d", strtotime("-7 days")); //On 2019-08-19, this resulted in 2019-08-12 echo $lastWeek;

In this case, we passed “-7 days” in as a parameter to the strtotime function.

This works because the strtotime function is pretty good at parsing textual date descriptions.

Here is an alternative solution for those of you who prefer to use the DateTime object:

//Today's date. $currentDate = new DateTime(); //Subtract a day using DateInterval $lastWeekDT = $currentDate->sub(new DateInterval('P1W')); //Get the date in a YYYY-MM-DD format. $lastWeek = $lastWeekDT->format('Y-m-d'); //Print out the result. echo $lastWeek;

Above, we set “P1W” as the $interval_spec parameter for DateInterval. This translates into “a period of one week.”

If you want to subtract two weeks instead of one, then you can change “P1W” to “P2W”.

Last month / -30 days.

Getting last month’s date can be tricky. This is because the number of days in a month can vary.

For example, the month of October has 31 days, while September has 30.

Take the following example:

//Last month $lastMonth = date("Y-m-d", strtotime("-1 month")); //On 2019-08-19, this resulted in 2019-07-19 echo $lastMonth;

The snippet above will work in most situations.

However, on October 31st, the function will actually return “October 1st” instead of “September 30th”.

This is because PHP’s strtotime function treats “-1 month” the same as “-30 days.”

If you want to get the previous month’s name or number, then you will need to use the following code instead:

//Get the first date of the previous month. echo date("Y-m-d", strtotime("first day of previous month"));

If you run the script above on October 31st, it will return September 1st.

As you can see, dealing with dates can be very tricky.

Источник

date_sub

Вычитает из времени объекта DateTime заданный интервал DateInterval.

Список параметров

Только для процедурного стиля: Объект DateTime, возвращаемый date_create(). Функция изменяет этот объект.

Возвращаемые значения

Возвращает объект DateTime для применения в цепи методов или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::sub()
$date = new DateTime('2000-01-20'); $date->sub(new DateInterval('P10D')); echo $date->format('Y-m-d') . "\n";
$date = date_create('2000-01-20'); date_sub($date, date_interval_create_from_date_string('10 days')); echo date_format($date, 'Y-m-d');

Результат выполнения данных примеров:

Пример #2 Другие примеры DateTime::sub()
$date = new DateTime('2000-01-20'); $date->sub(new DateInterval('PT10H30S')); echo $date->format('Y-m-d H:i:s') . "\n"; $date = new DateTime('2000-01-20'); $date->sub(new DateInterval('P7Y5M4DT4H3M2S')); echo $date->format('Y-m-d H:i:s') . "\n";

Результат выполнения данного примера:

2000-01-19 13:59:30 1992-08-15 19:56:58
Пример #3 Будьте внимательны при вычитании месяцев
$date = new DateTime('2001-04-30'); $interval = new DateInterval('P1M'); $date->sub($interval); echo $date->format('Y-m-d') . "\n"; $date->sub($interval); echo $date->format('Y-m-d') . "\n";

Результат выполнения данного примера:

Примечания

При работе с PHP 5.2 в качестве альтернативы можно использовать функцию DateTime::modify().

Смотрите также

  • DateTime::add() — Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
  • DateTime::diff() — Возвращает разницу между двумя DateTime объектами
  • DateTime::modify() — Изменение временной метки

Описание класса datetime, примеры использования класса datetime.

Источник

PHP вычитает 1 месяц из даты, отформатированной с датой (‘m-Y’)

Внимание! Приведенные выше примеры не сработают, если позвонить им в конце месяца.

Следующий пример даст тот же результат:

$date = new DateTime('2017-10-31 00:00:00'); echo $date->format('m-Y')."\n"; $date->modify('-1 month'); echo $date->format('m-Y')."\n"; 

Множество способов решения этой проблемы можно найти в другом потоке: PHP DateTime :: modify сложение и вычитание месяцев

Сначала измените формат даты с м-г на ​​г-м

 $date = $_POST('date'); // Post month or $date = date('m-Y'); // currrent month $date_txt = date_create_from_format('m-Y', $date); $change_format = date_format($date_txt, 'Y-m'); 

Этот код минус 1 месяц до указанной даты

 $final_date = new DateTime($change_format); $final_date->modify('-1 month'); $output = $final_date->format('m-Y'); 
$currentMonth = date('m', time()); $currentDay = date('d',time()); $currentYear = date('Y',time()); $lastMonth = $currentMonth -1; $one_month_ago=mkdate(0,0,0,$one_month_ago,$currentDay,$currentYear); 

Это можно было бы переписать более элегантно, но у меня это работает

В зависимости от вашей версии PHP вы можете использовать объект DateTime (введенный в PHP 5.2, если я правильно помню):

Вы можете передать конструктору другую дату, она не обязательно должна быть текущей датой. Дополнительная информация: http://php.net/manual/en/datetime.modify.php

$effectiveDate = date('2018-01'); 
echo 'Date'.$effectiveDate;
$effectiveDate = date('m-y', strtotime($effectiveDate.'+-1 months'));
echo 'Date'.$effectiveDate;

Я использовал это, чтобы предотвратить ошибку «последние дни месяца». Я просто использую второй strtotime (), чтобы установить дату на первый день месяца:

Источник

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?

  1. Create a date-time object, then use the modify function.
    • $dt = new DateTime(«2019-08-14»);
    • $dt->modify(«+4 days»);
    • $dt->modify(«-1 week»);
  2. 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»));
  3. 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

Add Subtract Days Weeks Months To A Date In PHP

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.

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!

Источник

Оцените статью