Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Last Day of Previous Month in PHP

Tags:

php

datetime

I'm a little unsure why this is not able to find the last day of the previous month. Every steps seems to be working correctly, except when the final date is created.

<?php  $currentMonth = date('n'); $currentYear = date('Y');  if($currentMonth == 1) {     $lastMonth = 12;     $lastYear = $currentYear - 1; } else {     $lastMonth = $currentMonth -1;     $lastYear = $currentYear; }  if($lastMonth < 10) {     $lastMonth = '0' . $lastMonth; }  $lastDayOfMonth = date('t', $lastMonth);  $lastDateOfPreviousMonth = $lastYear . '-' . $lastMonth . '-' . $lastDayOfMonth;  $newLastDateOfMonth = date('F j, Y', strtotime($lastDateOfPreviousMonth));  ?> 

$lastDateOfPreviousMonth is returning 2012-09-30 as expected; however, after trying to convert it to September 30, 2012 - $newLastDateOfMonth is returning October 1, 2012. Where do I seem to be going wrong?

EDIT: If using date("t/m/Y", strtotime("last month")); or date('Y-m-d', strtotime('last day of previous month')); will either of these still be viable given 2013-01-01, i.e. will they account for the change in year?

like image 887
William Orazi Avatar asked Oct 01 '12 13:10

William Orazi


People also ask

How can get first and last day of month in php?

php $dt = "2008-02-23"; echo 'First day : '. date("Y-m-01", strtotime($dt)). ' - Last day : '. date("Y-m-t", strtotime($dt)); ?>

What is Strtotime php?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

What is previous month?

previous month means the month or months immediately preceding the month for which a monthly report is due from qualified public depositories.


1 Answers

echo date('Y-m-d', strtotime('last day of previous month')); //2012-09-30 

or

$date = new DateTime(); $date->modify("last day of previous month"); echo $date->format("Y-m-d"); 

Later edit: php.net documentation - relative formats for strtotime(), DateTime and date_create()

like image 118
Mihai Iorga Avatar answered Sep 28 '22 08:09

Mihai Iorga