2011-09-17

First/last day of the month

2011.09.17.
Is the given date the first day of the month? Or maybe the last? Whatta silly question... of course not the first or last one! But sometimes it is useful to know or.. better let`s say, return "true" on that kind of questions.
I found that it could be done very easily with creating object from such string, returning parts, making new date value and done some comparing.
Ok, here are the steps-
$dateObj= new DateTime($datestring);
$currentDay=(int) $dateObj->format('d'); //make int not string. let`s get necessary date parts
$currentMonth=(int) $firstDate->format('m');
$currentYear=(int) $firstDate->format('y');

//let`s create another month value returning from the new date, where it is created from the day //before current date
$prevMonth = (int) date("m", mktime(0, 0, 0, $currentMonth, $currentDay-1, $currentYear));


//and finally - comparison
if ($currentMonth>$prevMonth)
{
return "true";  //if previous date is in the previous month, we have the first day of the month
//from date object parts you can make new date here based on your needs through mktime.
}
else
{
return "false";
}

and now - if we need to know is the date is the last day in the month.
$nextMonth = (int) date("m", mktime(0, 0, 0, $currentMonth, $currentDay+1, $currentYear));
if ($currentMonth<$nextMonth)

See the changes?

Nav komentāru:

Ierakstīt komentāru