PHP subtract 1 month from date formatted with date ('m-Y')
Asked Answered
K

11

45

I'm trying to subtract 1 month from a date.

$today = date('m-Y');

This gives: 08-2016

How can I subtract a month to get 07-2016?

Knockout answered 3/8, 2016 at 8:55 Comment(3)
@user1234 please don't abuse code blocks.Cloraclorinda
(DATE_SUB(curdate(), INTERVAL 1 MONTH))Basically
Does this answer your question? PHP strtotime: Get previous monthClausen
U
81
 <?php 
  echo $newdate = date("m-Y", strtotime("-1 months"));

output

07-2016
Undulate answered 3/8, 2016 at 9:0 Comment(4)
N.B.: before using this example, read the warning about the edge-cases belowInguinal
strtotime("-1 months") does not work if you have 31 days.Starknaked
as @FakhruddinUjjainwala pointed out I found a solution preventing this with a second strtotime(). Just look at my provided anwser.Wesleyanism
echo date('Y-m', strtotime('2021-07-31' . ' - 1 month')); check this this will return 2021-07.. similarly check for March 31st or March 30th and even March 29th too if not leap yearOse
I
22

Warning! The above-mentioned examples won't work if call them at the end of a month.

<?php
$now = mktime(0, 0, 0, 10, 31, 2017);
echo date("m-Y", $now)."\n";
echo date("m-Y", strtotime("-1 months", $now))."\n";

will output:

10-2017
10-2017

The following example will produce the same result:

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

Plenty of ways how to solve the issue can be found in another thread: PHP DateTime::modify adding and subtracting months

Inguinal answered 10/10, 2017 at 12:54 Comment(2)
The reason behind it does not work is because the following: What's last month of 2017-10-29? 2017-09-29. And last month of 2017-10-30? 2017-09-30. And what about last month of 2017-10-31? In theory 2017-09-31, but this day does not exist, and then it maps onto 2017-10-01.Landseer
The problem stated above by @XaviMontero can be solved with: $date->modify('first day of -1 month');Roughcast
R
10

Try this,

$today = date('m-Y');
$newdate = date('m-Y', strtotime('-1 months', strtotime($today))); 
echo $newdate;
Roughneck answered 3/8, 2016 at 9:0 Comment(3)
should have included that this is looping around as I want to get the last 12 months starting from the current month.Knockout
You can use it in loopRoughneck
it will not work and it's output 12-1969Romanist
S
8

Depending on your PHP version you can use DateTime object (introduced in PHP 5.2 if I remember correctly):

<?php
$today = new DateTime(); // This will create a DateTime object with the current date
$today->modify('-1 month');

You can pass another date to the constructor, it does not have to be the current date. More information: http://php.net/manual/en/datetime.modify.php

Sandstone answered 3/8, 2016 at 9:9 Comment(0)
M
2
$lastMonth = date('Y-m', strtotime('-1 MONTH'));
Microdot answered 15/6, 2019 at 20:29 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Pomerania
W
1

Try this,

$effectiveDate = date('2018-01'); <br> 
echo 'Date'.$effectiveDate;<br>
$effectiveDate = date('m-y', strtotime($effectiveDate.'+-1 months'));<br>
echo 'Date'.$effectiveDate;
Weakminded answered 26/6, 2019 at 10:8 Comment(0)
W
1

I used this to prevent the "last days of month"-error. I just use a second strtotime() to set the date to the first day of the month:

<?php
echo $newdate = date("m-Y", strtotime("-1 months", strtotime(date("Y-m")."-01")));
Wesleyanism answered 31/7, 2020 at 10:31 Comment(0)
C
0
if(date("d") > 28){
    $date = date("Y-m", strtotime("-".$loop." months -2 Day"));
} else {
    $date = date("Y-m", strtotime("-".$loop." months"));
}
Christoper answered 9/5, 2019 at 6:0 Comment(1)
This code wont skip the february even if am at the month end.Christoper
A
0

First change the date format m-Y to Y-m

    $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');

This code minus 1 month to the given date

    $final_date = new DateTime($change_format);
    $final_date->modify('-1 month');
    $output = $final_date->format('m-Y');
Accrete answered 25/6, 2019 at 7:35 Comment(0)
M
0
$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);

This could be rewritten more elegantly, but it works for me

Mom answered 29/12, 2019 at 7:53 Comment(1)
This won't work if the current month is JanuaryDan
P
0

I realize this is an old post, but I've been solving the same issue, and here is what I came up with to account for all the variability. This function is just trying to get relative dates, so same day of prior month, or last day of month if you are on the last day, regardless of exactly how many days a month has. So goal is given '2010-03-31' and subtract a month, we should output '2010-02-28'.

private function subtractRelativeMonth(DateTime $incomingDate): DateTime
{
    $year = $incomingDate->format('Y');
    $month = $incomingDate->format('m');
    $day = $incomingDate->format('d');
    $daysInOldMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    if ($month == 1) { //It's January, so we have to go back to December of prior year
        $month = 12;
        $year--;
    } else {
        $month--;
    }
    $daysInNewMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    if ($day > $daysInNewMonth && $month == 2) { //New month is Feb
        $day = $daysInNewMonth;
    }
    if ($day > 29 && $daysInOldMonth > $daysInNewMonth) {
        $day = $daysInNewMonth;
    }
    $adjustedDate = new \DateTime($year . '-' . $month . '-' . $day);
    return $adjustedDate;
}
Piscator answered 27/9, 2022 at 12:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.