Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamps of start and end of month

Tags:

How can one get the timestamps of the first and last minutes of any month using PHP?

like image 384
Kir Avatar asked Jan 15 '11 23:01

Kir


2 Answers

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

like image 116
Felix Kling Avatar answered Sep 22 '22 11:09

Felix Kling


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); 
like image 29
enobrev Avatar answered Sep 23 '22 11:09

enobrev