date

PHP:CSI - Date Is Less Than One Month Ago

Working with logic surrounding dates can sometimes be difficult and it's fairly common to come across really subtle date and time based bugs.

I was recently shown a bug in a PHP application that looks like it should be working at face value, but doesn't actually produce the correct result.

The issue in question was surrounding a date comparison. A collection of objects containing dates were compared in order to find those dates that were less than a month old. This worked fine in testing since all testing dates were less than a month old. After the system was in use for a number of months it became clear that the check wasn't working so further investigation was needed.

Round Timestamp To Nearest Time With PHP

If you want to create a "rounded" time stamp, for example, to the nearest 15 minutes use this as a reference:

Find The Number Of Days For A Given Month With PHP

There are two ways to find out the number of days for a given month. The first is to use the date() function in conjunction with the mktime() function to create a date and format this value as the number of days in a given month.

$monthDays = date("t",mktime(0, 0, 0, 12, 1, 2008));

The second way is to use the function cal_days_in_month(). This function takes three parameters.

PHP Function To Work Out Age From Date

Use the following function to work out how many years have passed since an event. This can be useful if you want to work out a persons age based on their birthday.

The function works by standardising the format of the date using the PHP strtotime() function. This is the first step of the function and sorts out if the date is valid or not. Once this has been done then the date is formatted into a standard form of yyyy-mm-dd, which is then split using the explode() function. The year of the inputted date is then subtracted from the current year, giving the age in years. A final check makes sure that the date hasn't passed yet, and subtracts one from the years value to give a more accurate result. Here is the function: