| ||||||
|
Manipulating PHP mktime() into returning next minute, hour, day, month or year
This page discuses how you can trick the PHP function mktime() into returning the Unix timestamp of a date within a specified distance in the future or from the past. To first illustrate this we will use the following example. We will call the example pizza.php. When loaded it will add 20 minutes to the current time, which is the exact time around the pizza should be ready. Without being burnt or undercooked ideally;-)! Here is how it is done: <?php $pizza = mktime(date("H"), date("i") + 20, date("s"), date("m"), date("d"), date("Y")); echo "Your Pizza will be ready at ".strftime("%H:%M:%S", $pizza); ?> Note that the key here is to add adding 20 to the minute specification: date("i") + 20 If you are not familiar with date(), here's a legend: Hours = date("H") Minutes = date("i") Seconds = date("s") Month = date("m") Day = date("d") Year = date("Y") Naturally this plus system works for every date element from hours and seconds, through to months, days and years: <?php $hourPlus4 = mktime(date("H") + 4, date("i"), date("s"), date("m") , date("d"), date("Y")); $dayPlus3 = mktime(date("H"), date("i"), date("s"), date("m") , date("d") + 3, date("Y")); $monthMinus5 = mktime(date("H"), date("i"), date("s"), date("m") - 5, date("d"), date("Y")); $yearMinus20 = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y") - 20); echo strftime("%c", $hourPlus4); echo "<br><br>"; echo strftime("%c", $dayPlus3); echo "<br><br>"; echo strftime("%c", $monthMinus5); echo "<br><br>"; echo strftime("%c", $yearMinus20); ?> Note that even though the Unix time started counting it's seconds from the 1st of January 1970 you can still go back further. Right now the largest gap you can time travel though is one hundred and seven years though, as the following example shows: <?php $yearMinus60 = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y") - 60); $yearMinus107 = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y") - 107); $yearMinus108 = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y") - 108); echo strftime("%c", $yearMinus60); echo "<br><br>"; echo strftime("%c", $yearMinus107); echo "<br><br>"; echo strftime("%c", $yearMinus108); ?> If you feel the need to go back any further you will have to make do without strftime, and find/create an alternative!
|