You Are Here Home > Server Performance

Server Performance

PHP Date/Time Handling Made Easy; a beginner’s guide to PHP time and date handling

When I started with PHP, I was a bit confused about this subject so this will hopefully help a beginner a lot.

UNIX Timestamp

UNIX Timestamp (or Unix time or POSIX time) is the number of seconds since the midnight of January 1, 1970 UTC.

You can get the current timestamp with PHP’s time() function:

<?php
	echo time();
?>

This will show you the number of seconds since January 1, 1970 UTC.

Assume that you are creating a blogging application using PHP and you want to save the time/date of the posts
with them, in your database, you can create a table like this:

CREATE TABLE IF NOT EXISTS `post` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
  `title` varchar(250) NOT NULL DEFAULT '',
  `body` text NULL DEFAULT '',
  `ip_address` varchar(30) NOT NULL DEFAULT '',
  `date` int(11) DEFAULT NULL,
  `last_update` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY  (`id`),
  KEY `date` (`date`),
  KEY `last_update` (`last_update`)
);

Now, a query to insert a blog post will look something like this:

<?php
 
$query = '
	INSERT INTO post
		(
			user_id,
			title,
			body,
			ip_address,
			date,
			last_update
		)
	VALUES
		(
			' .$user_id .',
			' .mysql_real_escape_string($_POST['title']) .',
			' .mysql_real_escape_string($_POST['body']) .',
			' .mysql_real_escape_string($_SERVER['REMOTE_ADDR']) .',
			' .time() ',
			' .time() '
		)
';
?>

(I left our details about filtering $_POST array out of this, you might want to filter the $_POST array a bit)

This way the query to get all the posts, sorted by date would look like:

SELECT *
FROM post
ORDER BY date DESC

A query to get all the posts from last 24 hours would look like:

<?php
$start_date = time() - (24 * 60 * 60);
$query = "
   SELECT *
   FROM post
   WHERE date >= $start_date
   ORDER BY date DESC
";
$result = mysql_query($query);
/* ... */
?>

A Performance Tip

If you don’t pay attention, you will end up with 100s of calls to time() throughout your application and we
know that function calls have overhead so what do you do?

We can call time only ONCE and save the results in a constant which will be global also, just like the time()
function:

<?php
	define('TIME_NOW', time());
?>

Converting UNIX Time To Readable Time

How do we show what time it is? That is in a format like: Mon, 15 Aug 2005 15:12:46

There is another useful function in PHP for this purpose and that is the date() function.

First you must set a default system timezone, it’s very simple, way on top of your scripts, (in your main include
fine perhaps) call this:

<?php
	date_default_timezone_set('EST');
?>

Don’t worry if you don’t understand what’s happening, this might help clear out a bit of the confusion:
http://www.php.net/manual/en/function.date-default-timezone-set.php

Again, read on and just add the line above on top of your script…

Now back to business, here is a simple call to the date() function:

<?php
	echo date('D/M/Y', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

This will show you something like:

Sun/Jan/2010

You can see that the first argument is a format in which you want the date to be, shown and the second argument is the timestamp of the date, if you don’t provide the second argument, the current timestamp will be used.

Here is another example that shows the time also:

<?php
	echo date('D/M/Y h:i:s A', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

Output:

Sun/Jan/2010 03:12:46 PM

These are some more examples: (taken from here)

<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
 
 
// Prints something like: Monday
echo date("l");
 
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
?>

I suggest that you read this page:

http://php.net/manual/en/function.date.php

Tip For Using The date() Function

You shouldn’t have lines like:

<?php
	echo date('D/M/Y h:i:s A', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

All over your code, why?

Because if you decide to change the way you show date, then you have to go around and edit all the lines containing:

<?php
	echo date('D/M/Y h:i:s A', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

To fix this, you could have a constant containing your date format string like:

<?php
	define('DATE_FORMAT', 'D/M/Y h:i:s A');
?>

Then in your code, you do this:

<?php
	echo date(DATE_FORMAT, TIME_NOW);
?>

Now if you want to change the format of the date throughout your PHP application, you can just edit the line with:

<?php
	define('DATE_FORMAT', 'D/M/Y h:i:s A');
?>

And it will magically change all of them!

Better yet, I would have a function like:

<?php
 
	function display_date($timestamp = NULL) {
		echo date('D/M/Y h:i:s A', $timestamp);
	}
 
?>

Or even better yet, you could have the function return the string as a value, so you have even greater control:

<?php
 
	function get_date_string($timestamp = NULL) {
		return date('D/M/Y h:i:s A', $timestamp);
	}
 
?>

Then call it like:

<?php
	echo get_date_string(TIME_NOW);
?>

The Pain Of Finding Out The Timestamp From A Formatted Date String

I made the pain part up, fortunately there is a function that does this very easily, it is strtotime()

<?php
	echo strtotime('9/25/2010 02:28:30 PM');
?>

And bam! magically, you will get the timestamp, it doesn’t end there, you can do things like this:

<?php
	echo strtotime('today'), "\n";
	echo strtotime('today + 1 day'), "\n";
	echo strtotime("now"), "\n";
	echo strtotime("10 September 2000"), "\n";
	echo strtotime("+1 day"), "\n";
	echo strtotime("+1 week"), "\n";
	echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
	echo strtotime("next Thursday"), "\n";
	echo strtotime("last Monday"), "\n";
?>

Read more about strtotime() here:

http://php.net/manual/en/function.strtotime.php

How To Display Dates Like ‘x days ago’?

I got this function form one of the comments on PHP documentation, it’s very nice and does just this:

<?php
	function date_range($timestamp) {
		if( $timestamp < 1 ) return '';
		$difference = time() - $timestamp;
		$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
		$lengths = array("60",     "60",     "24",   "7",   "4.35", "12",    "10");
		for($j = 0; $difference >= $lengths[$j]; $j++)
		$difference /= $lengths[$j];
		$difference = round($difference);
		if($difference != 1) $periods[$j].= "s";
		$text = "$difference $periods[$j] ago";
		return $text;
	}
?>

And call it like:

<?php
	echo date_range(strtotime('today - 1 day'));
?>

Back To The Blog Post Example

I will show you a quick example of displaying those blog posts we talked about in the beginning of this article with a nice formatted time:

<?php
$start_date = time() - (24 * 60 * 60);
$query = "
   SELECT *
   FROM post
   WHERE date >= $start_date
   ORDER BY date DESC
";
$result = mysql_query($query);
while ($post = mysql_fetch_assoc($result)) {
	echo "<strong>{$post['title']}</strong><br />";
	echo "{$post['body']}<br />";
	echo "Published: " .date_range($post['date']) ."<br /><br />";
}
?>

This is very simplistic but demonstrates the concept.

I hope this helps. If you liked it, help spread the word, it’s always appreciated.

Good Luck :)

PHP Date/Time Handling Made Easy; a beginner’s guide to PHP time and date handling
Comments (1)   Filed under: PHP,Server Performance,Web Development   Posted by: Hamid

How PHPCache saved us from buying another server

I developed a large website for a client and in the past month we were getting a lot of traffic.

It was in a way that the server had problems handling the traffic and my client wanted to get another server to load balance the traffic between the two.

Pages on this site are generated from 10 to 25 MySQL queries and these queries are optimized but consider this, if there are 1,000 request for a page with 25 queries in a very small period of time, that would be 25,000 queries. 25,000 queries + processing them could lead to huge server loads.

So we used PHPCache to cache the results of those queries for just 1 minute, not an hour or a day, just one minute and it made a huge difference.

The difference was that we cached all 25 queries plus the time it took to process them using PHPCache and now to handle 1,000 requests we were querying the database only 1,000 times.

I think this site can easily handle 10 times more traffic now.

How PHPCache saved us from buying another server
Comments (0)   Filed under: MySQL,PHP,Server Performance,Web Development   Posted by: Hamid
Older Posts »