PHP Get Prior Date or Yesterday

Here is a quickie to get the date prior to another date. You can make it one, two, 3 days prior. Doesn’t really matter. PHP’s mktime() function self corrects when you put in a day and subtract the number from it.
Yes. Even if it 2010-01-01 it will go return 2009-12-31.

function currWeek()
/**
 * Returns the date one day before the one entered, regardless of year or day of month.
 * Y-m-d
 * @return $dateBefore
 * @param object $mydate
*/
function getDayBefore($mydate){
	$mydate = explode("-", $mydate);
	$myyear 	= $mydate[0];
	$mymonth 	= $mydate[1];
	$myday		= $mydate[2];
	$dateBefore = mktime(0,0,0, $mymonth, $myday-1, $myyear);
	$dateBefore = date('Y-m-d',$dateBefore);
	return $dateBefore;
}

 

2 Responses to “PHP Get Prior Date or Yesterday”

  1. Dan says:

    Hi Eli,

    You can always use PHP’s strtotime() function, which converts a string into a timestamp, and you can also be less concerned about what format the date comes in.

    function daybefore($date){
    return date(’Y-m-d’, strtotime($date . ” -1 day”));
    }

  2. eligeske says:

    Thanks! I’ll have to check that out!

Leave a Reply