DATE OPERATIONS WITH MKTIME()
mktime() is a very versatile function.
But mktime() has another, less well known and incredibly useful feature: it can perform date-time operations.
Each of the function’s arguments represents a date-time component: hour, minute, second, month, day and year.
mktime() accepts any integer number for each component, including values outside of the valid range of that component. Even negative integers are accepted.
When a value is outside of the valid range, the function calculates the difference from the nearest valid value and then adds, or subtracts, an equal number of component units to the date-time before returning the Unix Timestamp.
It’s really easier to see how it works with a few examples:
<?php /* Get the Unix Time of the beginning of the next year */ mktime(0, 0, 0, 1, 1, date('Y') + 1); /* Yesterday at midnight; without worrying about day and month number or daylight saving time */ mktime(0, 0, 0, date('n'), date('j') - 1); /* 2 months from now, same day and time; without worrying about the number of days or daylight saving time */ mktime(date('H'), date('i'), date('s'), date('n') + 2); /* Midnight, last day of the last month; simply as the "day 0" of the current month */ mktime(0, 0, 0, date('n'), 0); /* 72 hours before now; without worrying about day/month/year changes or daylight saving time */ mktime(date('H') - 72);
Adding or subtracting date components can be really useful.
Suppose that you need to get the Unix Timestamp of “last day of the previous month”.
If you had to provide mktime() with the exact date-time components, you would need to get the current month number and subtract 1 from it, then check if it is 0 (meaning that we are in January, so you would have to set it to 12 and decrease the year by 1), then get the current day number and check how many days the previous month has…
It’s long and boring.
But thanks to mktime(), you can just set 0 as the day value to achieve the same result:
$time = mktime(0, 0, 0, date('n'), 0, date('Y'));
If you have any questions, feel free to ask in the comments below or on my Facebook Group: Alex PHP café.
If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!
MySQLi vs PDO: which one is best for you?
Get my weekly PHP tips and the bonus PDF, absolutely free.