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.
Working with PHP is easier than most people originally think. It is after all the general purpose scripting language used in web development. Once you understand the basics like time managment and databases, you can very easly produce dynamic web paging using it. Before you even consider setting up a webpage, it must be a priority to understand the basics of PHP. Hopefully you will find the following helpful and informative.
time() and date()
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.
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 prefer to think of it as:
string date ( string $format [, int $timestamp=time()] )
If you don’t pass the second parameter, it uses the
time() function instead.
Lets see a couple of examples:
// 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('it is the jS day.'); // 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 is month'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
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
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
In order to display it, use the
date() function, passing it as the second parameter.
- php timing
- php time