PHP - First and last day of last month.

Hi, I need to know the first and the last day of the current month and last month.

I use this:

   function firstOfMonth()
                        {
                            return date("Y-m-d H:i:s", strtotime(date('m') . '/01/' . date('Y') . ' 00:00:00'));
                        }
                        function lastOfMonth()
                        {
                            return date("Y-m-d H:i:s", strtotime('-1 second', strtotime('+1 month', strtotime(date('m') . '/01/' . date('Y') . ' 00:00:00'))));
                        }

to find out the first and the last date of the current month, but how do I find out the first and the last day of the last month?

Thank you.
VAL1NAsked:
Who is Participating?
 
Ray PaseurCommented:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

See: http://www.laprbass.com/RAY_temp_val1n.php

<?php // RAY_temp_val1n.php
error_reporting(E_ALL);
echo '<pre>';

// FROM THE POST AT EE
// Hi, I need to know the first and the last day of the current month and last month.

// REQUIRED PHP 5.1+
date_default_timezone_set('America/Chicago');

// TWO FUNCTION DEFINITIONS
function first_of_month($date = 'TODAY') { return date('Y-m-01', strtotime($date)); }
function  last_of_month($date = 'TODAY') { return date('Y-m-t',  strtotime($date)); }

// TEST CASES
echo PHP_EOL . first_of_month();
echo PHP_EOL . last_of_month();
echo PHP_EOL . first_of_month('-1 month');
echo PHP_EOL . last_of_month('-1 month');
echo PHP_EOL . first_of_month('+1 month');
echo PHP_EOL . last_of_month('+1 month');

Open in new window

HTH, ~Ray
0
 
Roger BaklundCommented:
The first day of a month should be easy, it is allways "01". So your firstOfMonth() function could have been simplified to something like this:

date('Y-m-01 00:00:00')

The PHP date() function has a special format character for finding the last date of a month:

date('Y-m-t 00:00:00')

The "t" format character will insert the number of days of the month, i.e. 28, 29, 30 or 31, depending on the month.

To check previous month (or any month), just provide a date as the second parameter for the date() function:

date('Y-m-t 00:00:00',strtotime('2012-07-01'))

http://no.php.net/manual/en/function.date.php
0
 
rajshekherCommented:
You can use this by passing the $month and $year for finding the first and last date of month.

$first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));
$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.