- [Voiceover] We've now learned what time zones are, and we learned how to set a default time zone in
PHP. Now in this chapter, we're ready to learn how to use them in our PHP code. The first thing you need to know about working with dates and times in PHP, is that PHP uses Unix time. Unix time is the number of seconds since
January 1, 1970, at
midnight,
UTC. So for example, the number 1451606400 is the number of seconds from January 1, 1970 at midnight UTC, until
January 1, 2016 at midnight, UTC.
So, dates are all represented by these numbers that tell us the number of seconds since that time. And PHP uses Unix time internally, it's sometimes referred to as a "time stamp." The easiest way to see it in action is just open up a new PHP file, and tell it to echo back the time
function. And that will provide you with the current Unix time, or the current time stamp. Unix time is really useful. It makes calculations super easy. For example, if we want to take a number of seconds, and we want to add to it a day, well then, we just take 60 for 60 seconds, times 60, for
60 minutes in an hour, times 24, for the number of hours in a day.
That's how many seconds there are in one day. So we just take that number, add the number of seconds for one day, and we come up with the new number. It also makes comparisons easy.
We can easily compare numbers to find out if one number is before another one. It makes it very easy to know if one date occurs before another date.
It's a question of how many seconds has it accrued since January 1, 1970 at midnight UTC. So even when you don't use Unix time as your input or your output, it's still going to be helpful to remember that this is how PHP works.
When you give PHP time in any format, it's going to convert it into Unix time. And when you ask PHP to output a date, PHP takes the Unix time and converts it to whatever format you've asked it to return. Now remember, Unix time is always in UTC, that's part of the definition. So the input or the output, PHP is going to use the specified time zone if you provide one, or the default time zone, if you don't specify another one. That's why that default time zone is so important.
Let's keep what we've learned about Unix time in mind as we continue to see the functions that PHP gives us for working with dates and times.
- published: 12 Mar 2016
- views: 0