sepehr
8/27/2013 - 9:16 AM

PHP: Get corresponding timestamp boundaries of a daterange

PHP: Get corresponding timestamp boundaries of a daterange

<?php

/**
 * Generates timestamp bounderies for the passed date range name.
 *
 * @param  string $range Date range name.
 *
 * @return array
 */
function get_daterange_timestamps($range)
{
	// Drop separators
	$range = str_replace(array('-', '_', ' '), '', $range);

	switch ($range)
	{
		case 'day':
		case 'today':
			return array(strtotime('today'), time());

		case 'yesterday':
		case 'previousday':
			return array(strtotime('yesterday midnight'), strtotime('today midnight') - 1);

		case 'last3days':
		case 'lastthreedays':
			return array(strtotime('2 days ago midnight'), time());

		case 'week':
		case 'thisweek':
			return array(strtotime('monday this week midnight'), time());

		case 'lastweek':
		case 'previousweek':
			return array(strtotime('monday previous week midnight'), strtotime('monday this week midnight') - 1);

		case 'month':
		case 'thismonth':
			return array(strtotime('first day of this month midnight'), time());

		case 'lastmonth':
		case 'previousmonth':
			return array(strtotime('first day of previous month midnight'), strtotime('first day of this month midnight') - 1);

		case 'year':
		case 'thisyear':
			return array(strtotime('first day of january this year midnight'), time());

		case 'lastyear':
		case 'previousyear':
			return array(strtotime('first day of january previous year midnight'), strtotime('last day of december previous year midnight') - 1);

		// Sinces:
		case 'sincelastweek':
			return array(strtotime('monday previous week midnight'), time());

		case 'sincelastmonth':
			return array(strtotime('first day of previous month midnight'), time());

		case 'sincelast3months':
		case 'lastthreemonths':
		case 'last3months':
			return array(strtotime('first day of 3 month ago midnight'), time());

		case 'sincelast6months':
		case 'lastsixmonths':
		case 'last6months':
			return array(strtotime('first day of 6 month ago midnight'), time());

		// Untils:
		case 'untillastmonth':
			return array(0, strtotime('first day of 1 month ago midnight') - 1);

		case 'untillast3months':
			return array(0, strtotime('first day of 2 month ago midnight') - 1);

		case 'untillast6months':
			return array(0, strtotime('first day of 5 month ago midnight') - 1);

		case 'all':
		case 'anytime':
		case 'all times':
			return array(0, time());

		default:
			return FALSE;
	}
}