How can one get the timestamps of the first and last minutes of any month using PHP?
You can use mktime
and date
:
$first_minute = mktime(0, 0, 0, date("n"), 1); $last_minute = mktime(23, 59, 59, date("n"), date("t"));
That is for the current month. If you want to have it for any month, you have change the month and day parameter accordingly.
If you want to generate it for every month, you can just loop:
$times = array(); for($month = 1; $month <= 12; $month++) { $first_minute = mktime(0, 0, 0, $month, 1); $last_minute = mktime(23, 59, 59, $month, date('t', $first_minute)); $times[$month] = array($first_minute, $last_minute); }
DEMO
With PHP 5.3, you can do
$oFirst = new DateTime('first day of this month'); $oLast = new DateTime('last day of this month'); $oLast->setTime(23, 59, 59);
In PHP 5.2
Note: as AllThecode pointed out in the comments below, this next example only works if you do the $oFirst
portion first. If you add +1 month
to new DateTime
the result will jump an extra month ahead on the last day of the month (as of php 5.5.9).
$oToday = new DateTime(); $iTime = mktime(0, 0, 0, $oToday->format('m'), 1, $oToday->format('Y')); $oFirst = new DateTime(date('r', $iTime)); $oLast = clone $oFirst; $oLast->modify('+1 month'); $oLast->modify('-1 day'); $oLast->setTime(23, 59, 59);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With