Client Login



Blog

Food for thought and inspiring minds

August 01, 2009

PHP date essentials

In my projects, I’m always using dates, but to make life easier, I’ve composed a list of the dates I use to help reference by name rather than by the code.

<?php
$today = strtotime('today');
$yesterday = strtotime( '-1 days' );
$beforeyesterday = strtotime('-2 days');
$lastweek = strtotime('-7 days');
$lastmonth = strtotime('-30 days');
$lastyear = strtotime('-365 days');
$showtoday = date('M d');
$showyesterday = date('M d', $yesterday);
$showweek = date('M d', $lastweek);
$showmonth = date('M', $lastmonth);
$showyear = date('Y', $lastyear);
$now = time();
?>

I hope this is helpful for other PHP coders out there.


February 23, 2009

Convert month name to a number

For the longest time, I’ve always come across this barrier. No pun intended. I wish there was an easier way to convert the month name to a number, but after searching, I came across this thanks to doodlebee from webmasterworld.

Here’s what we have as follows, just copy and paste it and obviously change the month name to whatever month you need and it’ll show up.

function getMonth($m) {
$monthnames = array(
01 => 'January',
02 => 'February',
03 => 'March',
04 => 'April',
05 => 'May',
06 => 'June',
07 => 'July',
08 => 'August',
09 => 'September',
10 => 'October',
11 => 'November',
12 => 'December');

for($i=1;$i<=12;$i++){
$i = sprintf("%02d",$i);
if(date("F", mktime(0, 0, 0, $i, 1, 0)) == $m){
$month_number = $i;
}
}
return $month_number;
}//end function

echo getMonth('March');
echo getMonth('December');

And vice versa

function getMonthNum($m) {
$monthnames = array(
'01' => 'January',
'02' => 'February',
'03' => 'March',
'04' => 'April',
'05' => 'May',
'06' => 'June',
'07' => 'July',
'08' => 'August',
'09' => 'September',
'10' => 'October',
'11' => 'November',
'12' => 'December');

return $monthnames[$m];
}//end function

echo getMonthNum('09');