Formation v2.2

Formation is a lightweight class that can build all necesssary elements for a form, process the posted data (post, get, request), validate the data based on a schema and finally return a cleaned result.

5 custom PHP functions: Date/Time

Wednesday, February 11th 2009, 8:03pm
Topics: Tutorials, PHP & MySQL
Tags: Datetime, Date, Time, Function, Php, Custom
Views: 7,089, Comments: 5

It is now time for my second post, in my series of "Basic/Common PHP functions that all programmers should know". The first series was about basic PHP strings and with this issue I am going to tackle 5 more functions for date and time. As always, I try to make my functions short but powerful, enjoy!

If you have any ideas for a series you want to see, or a type of function, be sure to send me an email using the contact page (in the footer), thanks!

Days Between
This function finds the difference in days between two dates. Each date must be a unix timestamp; if not my function will try to convert it to one. This could be modified to find the difference in weeks, seconds, etc.

/**
 * Finds difference in days between dates
 * @param int $start
 * @param int $finish
 * @return int
 */
function daysBetween($start, $finish) {
	if (!is_int($start))	$start = strtotime($start);
	if (!is_int($finish))	$finish = strtotime($finish);
	
	$diff = $finish - $start;
	$days = $diff / (24 * 3600);
	
	return round($days);
}


Get Age
This is a pretty simple function, in that it will find the persons age depending on the year given and the current year. The birth year could either be a string of '1988' (4 numeric characters) or the full date 1988-02-26.

/**
 * Gets the age of an individual
 * @param int $timeStamp
 * @return int
 */
function getAge($timeStamp) {
	$seconds = time() - strtotime($timeStamp);
	$year = 60 * 60 * 24 * 365;
	
	return floor($seconds / $year);
}


Get Date/Time in Timezones
Now this is something that could be done in many numerous ways, but mine simply takes the timezone difference (-8, 0, +6, etc) as the second argument, and then returns a unix timestamp. This function does not have any input checking (so make sure your arguments are correct before hand) and does not apply Daylight Savings Time.

/**
 * Gets a unix timestamp in certain timezones
 * @param int $timeStamp
 * @param int $timeZone
 * @return int
 */
function timeInZone($timeStamp, $timeZone = -8) {
	return strtotime(gmdate('Y-m-d h:i:sa', $timeStamp + (3600 * $timeZone)));
}


Date within a Timeframe
This function will take a date and check to see if it was within a certain date range and return a boolean value. My function will attempt to convert non unix timestamps to unix; be sure to pass the data correctly. Also you can leave the 3rd argument empty ($finish date) and the current time() will be used.

/**
 * Checks to see if a timestamp was within a timeframe
 * @param int $check
 * @param int $start
 * @param int $finish
 * @return boolean
 */
function withinTimeframe($check, $start, $finish = '') {
	if (!is_int($check))	$check = strtotime($check);
	if (!is_int($start))	$start = strtotime($start);
	
	if (empty($finish)) {
		$finish = time();
	} else {
		if (!is_int($finish)) $finish = strtotime($finish);
	}
	
	if ($check >= $start && $check <= $finish) {
		return true;
	}

	return false;
}


Breakdown a timestamp
Now this next function is quite different then the previous ones, but is pretty powerful. This function breaks down the timestamp to find how many days, weeks, months, etc there are until the current time (using time()). This type of function is good for doing text like: Last comment 5 days, 3 hours ago.

/**
 * Breaksdown a timestamp into an array of days, months, etc since the current time
 * @param int $timeStamp
 * @return array
 */
function timeBreakdown($timeStamp) {
	if (!is_int($timeStamp)) $timeStamp = strtotime($timeStamp);
	$currentTime = time();
	
	$periods = array(
		'years'         => 31556926,
		'months'        => 2629743,
		'weeks'         => 604800,
		'days'          => 86400,
		'hours'         => 3600,
		'minutes'       => 60,
		'seconds'       => 1
	);
	
	$durations = array(
		'years'         => 0,
		'months'        => 0,
		'weeks'         => 0,
		'days'          => 0,
		'hours'         => 0,
		'minutes'       => 0,
		'seconds'       => 0
	);
	
	if ($timeStamp) {
		$seconds = $currentTime - $timeStamp;
		
		if ($seconds <= 0){
			return $durations;
		}
		
		foreach ($periods as $period => $seconds_in_period) {
			if ($seconds >= $seconds_in_period) {
				$durations[$period] = floor($seconds / $seconds_in_period);
				$seconds -= $durations[$period] * $seconds_in_period;
			}
		}
	}
	
	return $durations;
}


And there you have it, 5 functions dealing with date and time. Stay tuned for the next issue! And again, if you have ideas for functions, send me an email!

5 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • Satbir Singh
    webdeveloperplus.com
    Mar 3rd 2009, 05:59
    1 Really useful functions. Now working with dates in php w'd be a breeze. Thanks
  • Jesper
    Mar 6th 2009, 16:33
    2 Would be useful if you wrote the echo part too so all the beginers can understand and use the code...
  • Saqib Hayat
    knowledgee...ogspot.com
    Apr 1st 2009, 09:13
    3 Really helped me alot when guiding my juniors,
    God Bless you
  • PiterKokoniz
    dev.winamp...get=Aldor4
    Apr 7th 2009, 16:38
    4 Hi ! :)
    I am Piter Kokoniz. oOnly want to tell, that your blog is really cool
    And want to ask you: is this blog your hobby?
    Sorry for my bad english:)
    Thank you!
    Piter.
  • buggedcom
    www.buggedcom.co.uk
    Jun 8th 2009, 22:50
    5 Some of your functions calculate days and seconds for certain periods, ie

    $year = 60 * 60 * 24 * 365;
    $days = $diff / (24 * 3600);

    Would you not be better of using the pre-calculated integer ie

    $year = 31536000;
    $days = $diff / 86400;