date

PHP Logo

Round Timestamp To Nearest Time With PHP

19th March 2010 - 1 minute read time

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

function roundTime($amount, $units = 'm', $time = null)
{
    if (is_null($time)) {
        $time = time();
    }
    
    if ($amount == 0) {
        $amount = 1;
    }
    
    switch ($units){ 
        case 'm':        
            $roundBy = 60 * $amount;
            break;
        case 'h':
            $time = $time + 60 * 60 * $amount;        
            $roundBy = 60 * 60 * $amount;
            break;
        case 'd':
            $time = $time + 60 * 60 * 24 * $amount;
            $roundBy = 60 * 60 * 24 * $amount;
            break;
    }

    return round($time / $roundBy) * $roundBy;
}

echo "\n";
echo date('r', roundTime(15, 'm'));
echo "\n";
echo date('r', roundTime(2, 'h'));
echo "\n";
echo date('r', roundTime(3, 'd'));
echo "\n";
echo date('r', roundTime(-3, 'd'));
echo "\n";
PHP Logo

Find The Number Of Days For A Given Month With PHP

10th October 2008 - 1 minute read time

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 Logo

PHP Function To Work Out Age From Date

1st September 2008 - 3 minutes read time

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: