How to get previous month and year relative to today, using strtotime and date?
Have a look at the DateTime
class. It should do the calculations correctly and the date formats are compatible with strttotime
. Something like:
$datestring='2011-03-30 first day of last month';
$dt=date_create($datestring);
echo $dt->format('Y-m'); //2011-02
Getting last month's date in php
It's simple to get last month date
echo date("Y-n-j", strtotime("first day of previous month"));
echo date("Y-n-j", strtotime("last day of previous month"));
at November 3 returns
2014-10-1
2014-10-31
PHP strtotime: Get previous month
strtotime("first day of last month")
The first day of
is the important part as detailed on the Relative Formats manual page.
Example: http://codepad.viper-7.com/dB35q8 (with hard-coded today's date)
How can i parse a date to same day of previous month?
<?php
$date = new DateTimeImmutable("2018-07-31");
$previous = $date->sub(new DateInterval('P1M'));
$lastMonth= $date->modify('last day of previous month');
if ($previous > $lastMonth) {
$previous = $lastMonth;
}
echo $previous ->format('Y-m-d');
This code subtracts one month from the current date. If it is greater than the last day of the previous month we use the last day of the previous month instead.
Demo
How to find the last day of the month from date?
t
returns the number of days in the month of a given date (see the docs for date
):
$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
How to determine start (date) of previous month in a time loop?
Quite easy:
$reference = strtotime('+70 days'); // this is what your simulation uses
$ts = strtotime('first day of last month', $reference);
echo date('Y-m-d', $ts);
The above code would show the first day of the month preceding the month 70 days from today in the specified format.
Related Topics
Warning: MySQLi_Query() Expects Parameter 1 to Be MySQLi, String Given In
How to Convert Boolean to String
Why and How to Use Anonymous Functions in PHP
Merge 'With' and 'Wherehas' in Laravel 5
Why Is Crontab Not Executing My PHP Script
How to Prepare Statement for Update Query
PHP Code to Test Pdo Is Available
Are the PHP Preg_Functions Multibyte Safe
Scroll Bar for Datalist in HTML5
How to Pass Jquery Variables to PHP Variable
Pg_Query Result Contains Strings Instead of Integer, Numeric
How to Upload and Parse a CSV File in PHP
How to Pass an Array via $_Get in PHP
Create an Encrypted Zip Archive with PHP
Is This a How to Destroy All Session Data in PHP
Php's JSON_Encode Does Not Escape All JSON Control Characters