Human readable string based time in seconds (for caching, delays etc)

Submitted by robjbrain - 7 months ago

This function will allow you to use human readable strings in place of integers when defining a time in seconds for caching, delays in jobs etc.

function cacheTime($expiresAt) {
    if (is_numeric($expiresAt)) {
        return $expiresAt;
    } else {
        return \Carbon\Carbon::parse($expiresAt, 'UTC')->diffInSeconds();
    }
}

// will cache for 600 seconds
Cache::put('key', 'value', cachetime('10 minutes'));

// will cache for 10800 seconds
Cache::put('key', 'value', cachetime('3 hours'));

// will cache for 1209600 seconds
Cache::put('key', 'value', cachetime('2 weeks'));

// will cache for 2419200 seconds
Cache::put('key', 'value', cachetime('1 month'));

// will definitely cache until next Thursday at 00:00
Cache::put('key', 'value', cachetime('next Thursday'));

// will definitely cache until whenever it is next 9pm
Cache::put('key', 'value', cachetime('9pm'));

// will definitely cache until the end of the month
Cache::put('key', 'value', cachetime('next month'));

// will definitely cache until the last day of of next month
Cache::put('key', 'value', cachetime('last day of next month'));
comments powered by Disqus