How to Get Previous Month and Year Relative to Today, Using Strtotime and Date

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



Leave a reply



Submit