Skip to content
Advertisement

Identify date format from a string in PHP

I am trying to update all of the date fields in the database to add 5 days to each date in all tables.

I managed to pull the dates and row id into an array then generate a SQL code statement to update them. However, each table has a different date format some with time included some without. I want to add 5 days to a date then save it back. At the moment I can do this if all dates have the same format but that’s not good enough to solve my problem.

What I want is a code that can generate string format from a date string. For example:

Date String 2014-12-04 I want the code to say this date has Y-m-d format. If date string is 2017-04-03 11:11:48.653 I want the code to say this date format is Y-m-d h:i:s.

Advertisement

Answer

If you don’t need to preserve the format (i.e. you can change the format in the database while adding five days), you can just throw the string at strtotime. It will try and detect the format, if possible:

$timestamp = strtotime($string_with_unknown_format);

Alternatively, you can check for different formats with regex:

function extractDateTimeFormat($string) {
    if (preg_match('/^d{4}-d{2}-d{2}$/', $string))
        return 'Y-m-d';

    if (preg_match('/^d{4}-d{2}-d{2} d{2}:d{2}:d{2}$/', $string))
        return 'Y-m-d H:i:s';

    if (preg_match('/^d{4}-d{2}-d{2} d{2}:d{2}:d{2}.d{3}$/', $string))
        return 'Y-m-d H:i:s.v';

    if (preg_match('/^d{2}/d{2}/d{4}$/', $string))
        return 'm/d/Y';

    if (preg_match('/^d{2}.d{2}.d{4}$/', $string))
        return 'd.m.Y';
}

However, that could get tiresome, depending on how many formats you expect. On the other hand – how many can there be?

The next alternative would be to replace the digits by their placeholders directly in the string – this would be more flexible, but possibly a little less predictable. In this case, the order of the lines is important. If you need to add 12 hour formats (AM / PM), you need to insert the lines prior to the line for H:i:s or it won’t work.

function extractDateTimeFormat($string) {
    $string = preg_replace('/bd{4}-d{2}-d{2}b/', 'Y-m-d');
    $string = preg_replace('/bd{2}/d{2}/d{4}b/', 'm/d/Y');
    $string = preg_replace('/bd{2}.d{2}.d{4}b/', 'd.m.Y');
    $string = preg_replace('/bd{2}:d{2}b:d{2}b/', 'H:i:s');
    $string = preg_replace('/bd{2}:d{2}b/', 'H:i');
    $string = preg_replace('/.d{3}b/', '.v');

    if (preg_match('/d/', $string) 
        return false;

    return $string;
}

That way, you’ll detect date and time formats independently so you don’t have to think of every possible combination.
You’ll have to check with your live data which method works better.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement