int mktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]])
It is a common tactic to store year, month, and day in separate variables in order to make comparison easier, and there is a special function for creating a Unix timestamp from date components: mktime().
Of all the functions in PHP, this one has perhaps the most unusual parameter ordering, so I would really recommend against trying to memorise the order in which they come - that is what this book and the online PHP manual are for! The order is this: hour, minute, second, month, day, year, Is_Daylight_Savings_Time. Note that "hour" should be in 24-hour clock time.
So, to pass in 10:30pm on the 20th of June 2005, you would use mktime() like this:
$unixtime = mktime(22, 30, 0, 20, 6, 2005, -1);
The only parameter there that might not make sense is the last one - this is where you tell PHP whether daylight savings time (DST) should be in effect. If this seems odd to you - surely PHP should know whether DST was in effect - consider the difficulties there are in calculating it. Each country enters DST at its own time, with some countries even having various times inside itself. Other countries, such as Germany, have only been using the DST system since 1980, which really complicates the matter. So, PHP gives you the option: pass 1 as the last parameter to have DST on, pass 0 to have it off, and pass -1 to let PHP take its best guess.
Using mktime() is a great way to do date arithmetic, as it will correct crazy dates quite well. For example, if we wanted to add 13 months to the function call above without having to figure out the new settings, we could just add 13 to the month parameter (currently 6), like this:
$unixtime = mktime(10, 30, 0, 19, 20, 2005, -1);
Clearly there are not 19 months in the year, so PHP will add one to the year value, subtract 12 from the months value, and calculate the date from there. Similarly you could add 9990 to the hours value and PHP will jump ahead by 416 days.
Author's Note: All the parameters, if less than 10, should not be expressed with a leading zero. The reason for this is that numbers with a leading zero are interpreted by PHP as being octal numbers, and this is likely to cause unforeseen results. For example, saying 08 for the eighth day will be interpreted in octal, and the highest single-digit value in octal numbers is 7, so PHP will set the number as 0.
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Mathematics >>
Previous chapter: Converting to a string
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.