0
votes

I need to get last day-name's date and last month-name's date in PHP.

For days, i did the following which is working fine :

echo date('Y-m-d', strtotime("last Monday"));    // Last Monday Date
echo date('Y-m-d', strtotime("last Tuesday"));   // Last Tuesday Date
echo date('Y-m-d', strtotime("last Wednesday")); // Last Wednesday Date
echo date('Y-m-d', strtotime("last Thursday"));  // Last Thursday Date
echo date('Y-m-d', strtotime("last Friday"));    // Last Friday Date
echo date('Y-m-d', strtotime("last Saturday"));  // Last Saturday Date 
echo date('Y-m-d', strtotime("last Sunday"));    // Last Sunday Date 

How can i do for previous months which is not working :

echo date('Y-m-d', strtotime("last January"));  // Last January Date
echo date('Y-m-d', strtotime("last February")); // Last February Date
....

I can not use date('Y-m-d', strtotime('last month')) because it can be any month when i need my previous January or February dates. For example, i need last January's date in September.

EDIT : My solution is

// Today : 2016-09-05
echo date('Y-m', strtotime("first day of January"));  // Output : 2016-01
echo date('Y-m', strtotime("first day of February")); // Output : 2016-02
echo date('Y-m', strtotime("first day of March"));    // Output : 2016-03
....
echo date('Y-m', strtotime("-1 year first day of January"));  // Output : 2015-01
echo date('Y-m', strtotime("-1 year first day of February")); // Output : 2015-02
echo date('Y-m', strtotime("-1 year first day of March"));    // Output : 2015-03

It is not exactly what i asked in my question, especially with months after the current one. Eg: first day of December while we are in September is NOT the last Septembre and is in the future but it do the trick for me because i have the correct year.

3

3 Answers

1
votes

i believe you can do something like

$date = new DateTime('last day of last month');

http://www.php.net/manual/de/datetime.formats.relative.php#102947

0
votes
echo date("Y-m-d", strtotime("first day of previous month"));
echo date("Y-m-d", strtotime("last day of previous month"));

Getting last month's date in php

0
votes

you can use this for find last day of previous month

date('Y-m', strtotime('first day of last month'));
 echo date('Y-m-d', strtotime("first day of -1 month"));

and this is for previous month

echo date("Y-m-d H:i:s",strtotime("-1 month"));

and last day of previous month

echo date('Y-m-d', strtotime("last day of -1 month"));
echo date('Y-m-d', strtotime("last day of last month"));