Lesson 4: Working with time and dates

In this lesson, we will try to look at the many different options for working with time and dates in PHP. We went through some very simple examples in the previous lesson mostly to show you what PHP is. In this lesson, we will take a closer look at the date function.

Time expressed in the number of seconds since January 1, 1970, 12:00 PM GMT is a so-called "timestamp" (UNIX timestamp) and is quite useful when you work with dates/times in the future or the past.

By default, the date function uses the current timestamp (i.e. the current value of time()). But with an extra parameter you can specify a different time stamp and thus work with the future or the past. In the example below, we set the timestamp to 0 seconds from January 1, 1970 12:00 PM, GMT. Thereby we can check what day of week January 1, 1970 was.

Unless you are a mathematical genius, it quickly becomes complicated to count the number of seconds since January 1, 1970 to a specific time in the future or past. But here you can get help from another nifty function: mktime, which does the calculations for you.

The syntax for mktime is (hour, minute, second, month, day, year). The example below converts the time of the first step on the Moon (July 21, 1969, 02:56):

What can you use it for?

All this may seem a bit theoretical at this stage. After all, what on earth can you use a function like time() for? More importantly, when will you learn something you can actually use on your pages?

The answer is that what you learn here are building blocks - the only limitations to what you can build are your creativity and imagination! I would venture to say that you have already learned more than you think. For example, do you think you can make a website with different background images each day of the week and that works in all browsers?