How can one get the timestamps of the first and last minutes of any month using PHP?
$date = new \DateTime('now');//Current time
$date->modify("-1 month");//get last month
$startDate = $date->format('Y-m-01');
$endDate = $date->format('Y-m-t');
I think better then
$first_minute = mktime(0, 0, 0, date("n"), 1);
$last_minute = mktime(23, 59, 0, date("n"), date("t"));
is:
$first_minute = mktime(0, 0, 0, date("n"), 1);
$last_minute = mktime(23, 59, 0, date("n") + 1, 0);
This requires PHP > 5.2 and need adjustement for the "minutes" part
$year = ...; // this is your year
$month = ...; // this is your month
$month = ($month < 10 ? '0' . $month : $month);
$start = new DateTime($year . '-' . $month . '-01 00:00:00');
$end = $start->modify('+1 month -1 day -1 minute'); //perhaps this need 3 "->modify"
echo $start->format('U');
echo $end->format('U');
(not tested)
Ref: http://www.php.net/manual/en/class.datetime.php
Best Way do like this..
$first_day = date('m-01-Y h:i:s',strtotime("-1 months"));
$last_day = date('m-t-Y h:i:s',strtotime("-1 months"));
Use mktime for generating timestamps from hour/month/day/... values and cal_days_in_month to get the number of days in a month:
$month = 1; $year = 2011;
$firstMinute = mktime(0, 0, 0, $month, 1, $year);
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$lastMinute = mktime(23, 59, 0, $month, $days, $year);
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