PHP Date functions

From Code Trash
Jump to: navigation, search

Date Difference - No of days between two dates

function getDays($fromdate,$todate)
	$a = split('-',$fromdate);
	$one = mktime(0,0,0,$a[1],$a[2],$a[0]);
	$a = split('-',$todate);
	$two = mktime(0,0,0,$a[1],$a[2],$a[0]);	
	return ($two-$one)/86400;
//this is giving fractional values like 17.9587989 if it is 18 day difference... so... you can use the round function or the following...
	$res = mysql_query("select DATEDIFF('$todate','$fromdate') as diberance");
	$res = mysql_fetch_array($res);
	$res = $res['diberance'];
	return $res;

Array list of dates between two dates

function getSeqDays($in,$out)
	$nodays = getDays($in,$out);
	$sdate = date2number($in);
	// i=1 for lastdate-1 . i=0 to include the last date.
		$sqdays[] = number2date($sdate);
	return $sqdays;

Date format to timestamp

function date2number($in)
	list($year,$month,$day) = split('-',$in);
	return mktime(0,0,0,$month,$day,$year);	

Timestamp to date format

function number2date($in)
	return date('Y-m-d',$in);

Add 1 month to date or timestamp

//I'm trying to figure out how I can add 1-month on to a "2008-05-09" style date. But I am //converting that date to a Unix timestamp first by doing the following:
$capturedDate = '2008-06-20';
$endDate = strtotime($capturedDate);
// Now I need to add 1 month onto $endDate.
//Anyone know how I can add 1-month onto $endDate using php? I've been looking high and low in the //php manual under date/time functions, but can't find anything that will do it with a unix //timestamp. Thanks for any help.
//Use strtotime again
$endDate = strtotime('+1 month',$endDate); 
// the other way is to do this
$timestamp = $timestamp + ($no_of_days_remining_of_current_month * 86400)