Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP strftime() using date() format string

I'm maintaining PHP code which seems to mess up date/time handling rather badly. In particular this application does not work well in other locales.

One of the issues is the use of the non-localizable date() function instead of the strftime() function. It is used several layers deep inside function which are literally used thousands of times with many different format strings all over the place.

Replacing date() with strftime() would cost way too much time. Rather I'm looking into ways to have strftime() handle the same format strings as date(), but can't find anything. Is there any known solution to use strftime() with date() format strings?

like image 569
Martijn Avatar asked Mar 26 '26 13:03

Martijn


1 Answers

/**
 * Convert strftime format to php date format
 * @param $strftimeformat
 * @return string|string[]
 * @throws Exception
 */
function strftime_format_to_date_format($strftimeformat){
    $unsupported = ['%U', '%V', '%C', '%g', '%G'];
    $foundunsupported = [];
    foreach($unsupported as $unsup){
        if (strpos($strftimeformat, $unsup) !== false){
            $foundunsupported[] = $unsup;
        }
    }
    if (!empty($foundunsupported)){
        throw new \Exception("Found these unsupported chars: ".implode(",", $foundunsupported).' in '.$strftimeformat);
    }
    // It is important to note that some do not translate accurately ie. lowercase L is supposed to convert to number with a preceding space if it is under 10, there is no accurate conversion so we just use 'g'
    $phpdateformat = str_replace(
        ['%a','%A','%d','%e','%u','%w','%W','%b','%h','%B','%m','%y','%Y', '%D',    '%F',   '%x', '%n', '%t', '%H', '%k', '%I', '%l', '%M', '%p', '%P', '%r' /* %I:%M:%S %p */, '%R' /* %H:%M */, '%S', '%T' /* %H:%M:%S */, '%X', '%z', '%Z',
            '%c', '%s',
            '%%'],
        ['D','l', 'd', 'j', 'N', 'w', 'W', 'M', 'M', 'F', 'm', 'y', 'Y', 'm/d/y', 'Y-m-d', 'm/d/y',"\n","\t", 'H', 'G', 'h', 'g', 'i', 'A', 'a', 'h:i:s A', 'H:i', 's', 'H:i:s', 'H:i:s', 'O', 'T',
            'D M j H:i:s Y' /*Tue Feb 5 00:45:10 2009*/, 'U',
            '%'],
        $strftimeformat
    );
    return $phpdateformat;
}

I wrote this function because none of the answers above sufficed. Handles most conversions -- easily extendable.

@see https://www.php.net/manual/en/function.date.php and https://www.php.net/manual/en/function.strftime.php

like image 132
relipse Avatar answered Mar 29 '26 04:03

relipse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!