[ Team LiB ] Previous Section Next Section

Getting the Date with time()

PHP's time() function gives you all the information you need about the current date and time. It requires no arguments but returns an integer. This number is a little hard on the eyes, for us humans, but extremely useful nonetheless:

print time();
// sample output: 1061577460

The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the Unix epoch, and the number of seconds that have elapsed since then is referred to as a timestamp. PHP offers excellent tools to convert a timestamp into a form that humans are comfortable with. Even so, isn't a timestamp a needlessly convoluted way of storing a date? In fact, the opposite is true. From just one number, you can extract enormous amounts of information. Even better, a timestamp can make date arithmetic much easier than you might imagine.

Think of a homegrown date system in which you record days of the month, as well as months and years. Now imagine a script that needs to add one day to a given date. If this date happened to be December 31, 1999, rather than add 1 to the date, you would have to write code to set the day of the month to 1, the month to January, and the year to 2000. Using a timestamp, you need only add a day's worth of seconds to your current figure, and you are done. You can convert this new figure into something more friendly at your leisure.

    [ Team LiB ] Previous Section Next Section