Search code examples
phpdatetimedate-formattingtext-parsing

Parse and reformat a datetime string


I have a string sent from database, I want to turn it into a date/time string. The source string is:

20110524153631

I want it to be:

2011-05-24 15:36:31

I know I can use multiple inserts but I want to know whether there's a more easy way to do this. How can I achive this?


Solution

  • In PHP 5.3 you can use the DateTime::createFromFormat() method (or its date_create_from_format() alias).

    echo DateTime::createFromFormat(
        'YmdHis',
        '20110524153631'
    )->format('Y-m-d H:i:s');
    

    For earlier versions (why?) you could play around with the string in any number of boring, or fanciful, ways.

    vprintf("%s-%s-%s %s:%s:%s", sscanf("20110524153631", "%4s%2s%2s%2s%2s%2s"));