Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I minus one month from Year-Month 2019-03

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

like image 279
Shareque Avatar asked Mar 05 '19 04:03

Shareque


People also ask

Can Excel add and subtract dates?

You can add or subtract a number of days to or from a date by using a simple formula, or you can use worksheet functions that are designed to work specifically with dates in Excel.


3 Answers

You can try the following solution:

date('Y-m', strtotime($payroll['month'] . ' - 1 month'))
like image 55
luffy1727 Avatar answered Oct 06 '22 01:10

luffy1727


Try this -

echo $newdate = date('Y-m', strtotime('-1 months', strtotime($payroll['month'])));
like image 37
Shubham Baranwal Avatar answered Oct 06 '22 01:10

Shubham Baranwal


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.

like image 41
Pupil Avatar answered Oct 06 '22 00:10

Pupil