I have date in a string as follows:
$rawDate = "08/08/2017 - 21/09/2017";
To separate two dates from each other I used code as:
$dates = explode("-", $rawDate);
Now I want to print dates as Date1 and Date2 as follows:
$date1 = date('Y-m-d', strtotime($dates[0]));
echo "Date 1: " . $date1;
echo "<br/>";
$date2 = date('Y-m-d', strtotime($dates[1]));
echo "Date 2: " . $date2;
I want result as
Date 1: 2017-08-08
Date 2: 2017-09-21
But I am getting result as
Date 1: 2017-08-08
Date 2: 2017-01-01
Can anyone help me how this is happening??
Try this..
$rawDate = "08/08/2017 - 21/09/2017";
$dates = explode(" - ", $rawDate);
$date1 = date('Y-m-d', strtotime(str_replace('/','-',$dates[0])));
echo "Date 1: " . $date1;
echo "<br/>";
$date2 = date('Y-m-d', strtotime(str_replace('/','-',$dates[1])));
echo "Date 2: " . $date2;
Life is a lot easier working with dates if you use DateTime objects, because it's easy to specify the format you're receiving the dates
$rawDate = "08/08/2017 - 21/09/2017";
$dates = explode("-", $rawDate);
$date1 = DateTime::createFromFormat('d/m/Y', trim($dates[0]));
echo "Date 1: " . $date1->format('Y-m-d');
echo PHP_EOL;
$date2 = DateTime::createFromFormat('d/m/Y', trim($dates[1]));
echo "Date 2: " . $date2->format('Y-m-d');