Search code examples
phpdateformatdate-rangedate-parsing

How to reformat "d-m-Y - d-m-Y" string to "Y-m-d Y-m-d"?


I want to change the format of a string containing two d-m-Y date strings separated by space hyphen space (representing a range). The desired output should have a format of Y-m-d - Y-m-d.

I can successfully execute a similar technique with d/m/Y - d/m/Y strings, but something isn't right when I am parsing the format of these new strings.

My code:

$date = "25-05-2020 - 30-05-2020";

$string = explode('-', $date);
$date1 = explode('-', $string[0]);
$date2 = explode('-', $string[1]);

$date1 = $date1[2] . '-' . $date1[0] . '-' . $date1[1];
$date2 = $date2[2] . '-' . $date2[0] . '-' . $date2[1];

echo $date1 . ' - ' . $date2;

My desired output from the sample input is 2020-05-25 - 2020-05-30.


Solution

  • Just add a space before and after - like below:

    <?php
    
    $date = "25-05-2020 - 30-05-2020";
    $splitted_dates = explode(" - ",$date);
    $date1 = $splitted_dates[0];
    $date2 = $splitted_dates[1];
    
    echo $date1, " " , $date2;
    

    Demo: https://3v4l.org/QTIHd