5

I am trying to subtract one month from the current receiving year-month (2019-03)

echo $payroll['month'];
echo $newdate = date("Y-m", strtotime("-1 months",$payroll['month']));

but it through error as

2019-03

A PHP Error was encountered

Severity: Notice

Message: A non well formed numeric value encountered

what I want 2019-03 to subtract one month so I will get 2019-02

Community
  • 1
  • 1
Shareque
  • 361
  • 4
  • 23

5 Answers5

3

You can try the following solution:

date('Y-m', strtotime($payroll['month'] . ' - 1 month'))
Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40
luffy1727
  • 39
  • 2
2

Try this -

echo $newdate = date('Y-m', strtotime('-1 months', strtotime($payroll['month'])));
Shubham Baranwal
  • 2,492
  • 3
  • 14
  • 26
2

So many nice answers here.

Just note that this can be done with PHP's DateTime class.

$date = new DateTime("2019-03-03");
$date->sub(new DateInterval('P1M')); // P -> Period 1 Month
echo $date->format("Y-m")
// Outputs: 2019-02

A quick note from strtotime() 's official documentation.

Note: Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

Pupil
  • 23,834
  • 6
  • 44
  • 66
0

You can add one more strtotime to get your desired output

$payroll['month'] = "2019-03";
echo $payroll['month'];
echo $newdate = date("Y-m", strtotime("-1 months", strtotime($payroll['month'])));

Another way to do the same is:

date('Y-m', strtotime($payroll['month'] . '-1 months'))

This will also work for you.

Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40
0

Beware... simply adding or substracting one month on a yyyy-mm string may render unexpected results under some edge cases. It happens that I use that format on a site I built (for payrolls and other stuff) and when the calculation was done on February 28 (IIRC) and other edge cases, the result wasn't always what I needed it to be (i.e., the next or previous month)

It's a little bit more code, but my advice would be:

$first_of_month = date('Y-m-01', strtotime($payroll['month']));
$newdate = date('Y-m', strtotime($first_of_month."-1 month"));

By forcing your initial value to be a full Y-m-d date on the first day of the month (the day being irrelevant for you, as it's used only for the calculation) you can make sure that the calculation will be correct every time

Javier Larroulet
  • 3,047
  • 3
  • 13
  • 30