-2

I would like to convert a date that comes in the format 06.11.2017 um 18:30 - 21:30 Uhr into the format 2017-11-06. So everything should be cut off after 06.11.2017 and the remaining date should be output in the format YYYY-MM-DD.

Is there an elegant way to do that?

Codehan25
  • 2,704
  • 10
  • 47
  • 94

4 Answers4

1

Not elegant but easy to implement :

 function formatDate($date) {
     $date = explode(' ', $date);
     $date = explode('.', $date[0]);

     return $date[2] .'-'. $date[1] .'-'. $date[0];
 }

 echo formatDate('06.11.2017 um 18:30 - 21:30 Uhr');
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
1
$date = "06.11.2017 um 18:30 - 21:30 Uhr";
$date = explode(" ",$date);

 if(array_key_exists(0,$date))
     echo date("Y-m-d", strtotime($date[0]));

output: 2017-11-06

  • Explode the string
  • Convert the first part to the desired format.
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
  • 1
    I have chosen your solution. Thanks a lot for this :). Thanks, of course, to all the others who have posted a solution. – Codehan25 Nov 27 '17 at 08:27
1

You can do it by using Explode function of PHP to cut the unwanted date and then change its format.

Below PHP code can help:

<?php
$date = "06.11.2017 um 18:30 - 21:30 Uhr";
$dateArr = explode(" ",$date);
$wantedDate = $dateArr[0];
$newDate = date("Y-m-d", strtotime($wantedDate));
echo $newDate;
// Output will be 2017-11-06
?>
Amit Gupta
  • 2,771
  • 2
  • 17
  • 31
0

Assuming your date string is always on that format, use substr() to cut the string then format the date to 'Y-m-d'

$date = '06.11.2017 um 18:30 - 21:30 Uhr';
$date = substr($date, 0, 10); // cut string to take date
$date = new DateTime($date);  // set string as datetime object
echo $date->format('Y-m-d');  // formatted date (2017-11-06)
Goma
  • 2,018
  • 1
  • 10
  • 19