Get the beginning and ending unix timestamp for a given month and year in php

Posted on

Get the beginning and ending unix timestamp for a given month and year in php – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and unix . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about Get the beginning and ending unix timestamp for a given month and year in php.

I want to find the timestamp for the first day in a month (say September 1 2010 and 0:00) and the last day in a month (say September 31 23:59).

Solution :

If you have those dates as strings you can simply use strtotime(), if you have only partial information you can use mktime().

However, September only has 30 days 😉

Example:

$month = 9;
$year  = 2010;

$first = mktime(0,0,0,$month,1,$year);
echo date('r', $first);

$last = mktime(23,59,00,$month+1,0,$year);
echo date('r', $last);

If you are using PHP 5.3 (don’t try this with 5.2, date parser works differently there) you could to the speaking:

<?php

$date = "2010-05-10 00:00:00";

$x = new DateTime($date);

$x->modify("last day of this month");
$x->modify("last second");

echo $x->format("Y-m-d H:i:s");
// 2010-05-30 23:59:59
$timestamp = $x->getTimestamp();

Maybe it can be done simpler but you get the idea:

<?php

$start = mktime(0, 0, 1, $month, 1, $year);
$end   = mktime(23, 59, 00, $month, date('t', $month), $year);

?>

Leave a Reply

Your email address will not be published. Required fields are marked *