Search code examples
phpdatetimetimestamp-with-timezone

Finding midnight of a timezone given offset in minutes [PHP]


I have an offset from UTC stored in minutes: e.g -240

I'm trying to find the corresponding UNIX timestamp of midnight of the current day for this particular offset.

I found similar information in questions like this one: How do I get the UTC time of "midnight" for a given timezone?

However, I don't have the city name/timezone jurisdiction, just a minute offset. I think this should be fine since for my purposes I don't need to account for daylight savings, it can be off by an hour and still be fine.

Examples

Offset: -420

Midnight on 7/12/2014: 1405148400 (unix TS)

With UTC, I would have to first tell if it's the next day or same day as the TZ because it may have a different "last midnight".


Solution

  • I had to think through it quite a bit, but I think this was the solution I was looking for. Let me know if you think this algorithm is incorrect.

    function getLastMidnightForOffset( $minuteOffset ) {
        $today = mktime( 0, 0, 0 );
        $tomorrow = $today + 86400;
        $yesterday = $today - 86400;
        $offset = $minuteOffset * 60;
    
        if ( time() + $offset >= $tomorrow ) {
            $localMidnight = $tomorrow - $offset;
        } elseif ( time() + $offset >= $today ) {
            $localMidnight = $today - $offset;
        } else {
            $localMidnight = $yesterday - $offset;
        }
    
        return $localMidnight;
    }