PHP Timing

Lately a fellow web developer of mine asked me why can’t he manage to save the current time in a MySQL table. The problem was that he didn’t understand how the PHP timing mechanism works. That’s why I decided to write this article.

time() and date()

time()

The time() function receives no parameters and returns the current time measured in the number of seconds since January 1 1970 00:00:00 GMT.
This may sound a bit weird but I find it to be clever.

Because one doesn’t want to display dates and times in PHP as a very long number (e.g. “The current time is 1256702873″), the date() function was created.

date()

The date() function returns a string formatted according to the given format parameter.

The function is documented as follows:
string date ( string $format [, int $timestamp ] )
While I’d prefer to think of it as
string date ( string $format , int $timestamp=time())
Because if you don’t pass the second parameter, it uses the time() function instead.

Lets see a couple of examples:
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date(‘h-i-s, j-m-y, it is w Day’); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date(‘\i\t \i\s \t\h\e jS \d\a\y.’); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date(‘H:m:s \m \i\s\ \m\o\n\t\h’); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
?>

I don’t want to get into the format parameter, but you can read about it at the PHP manual.

Saving the time in a MySQL Database

The wrong way

My friend was using some sort of a special “date”/”time”/”timestamp”/”datetime” column type because he didn’t know what he was getting from the time() function.
This is not the way to store the result from time(). While it may be useful in certain circumstances, I’d rather save the number of seconds since January 1 1970 00:00:00 GMT for later easier manipulation with PHP.

The right way

All you need to do is use a simple INT or BIGINT column type to store what you get from your time() call and in order to display it, use the date() function, passing it as the second parameter.

We will be happy to hear your thoughts

Leave a reply

TechEggs
Logo