Search code examples
phptimestampstrtotimeunix-timestamp

Given a Unix timestamp, how to get beginning and end of that day?


I have a Unix timestamp like this:

$timestamp=1330581600

How do I get the beginning of the day and the end of the day for that timestamp?

e.g.
$beginOfDay = Start of Timestamp's Day
$endOfDay = End of Timestamp's Day

I tried this:

$endOfDay = $timestamp + (60 * 60 * 23);

But I don't think it'll work because the timestamp itself isn't the exact beginning of the day.


Solution

  • strtotime can be used to to quickly chop off the hour/minutes/seconds

    $beginOfDay = strtotime("today", $timestamp);
    $endOfDay   = strtotime("tomorrow", $beginOfDay) - 1;
    

    DateTime can also be used, though requires a few extra steps to get from a long timestamp

    $dtNow = new DateTime();
    // Set a non-default timezone if needed
    $dtNow->setTimezone(new DateTimeZone('Pacific/Chatham'));
    $dtNow->setTimestamp($timestamp);
    
    $beginOfDay = clone $dtNow;
    $beginOfDay->modify('today');
    
    $endOfDay = clone $beginOfDay;
    $endOfDay->modify('tomorrow');
    // adjust from the start of next day to the end of the day,
    // per original question
    // Decremented the second as a long timestamp rather than the
    // DateTime object, due to oddities around modifying
    // into skipped hours of day-lights-saving.
    $endOfDateTimestamp = $endOfDay->getTimestamp();
    $endOfDay->setTimestamp($endOfDateTimestamp - 1);
    
    var_dump(
        array(
            'time ' => $dtNow->format('Y-m-d H:i:s e'),
            'start' => $beginOfDay->format('Y-m-d H:i:s e'),
            'end  ' => $endOfDay->format('Y-m-d H:i:s e'),
        )
    );
    

    With the addition of extended time in PHP7, there is potential to miss a second if using $now <= $end checking with this. Using $now < $nextStart checking would avoid that gap, in addition to the oddities around subtracting seconds and daylight savings in PHP's time handling.