0

I'm trying to convert a date and time variable into date only in a different format:

$test_date = '01/07/2018 10:00-12:00';
$result = substr($test_date, 0, 10);
$newDate = date("Ymd", strtotime($result));
echo $newDate;

Expected result= 20180701 Actual result= 20180107

Tried all the relative variations I can find on here but keep getting 'Ydm' instead of 'Ymd'.

I'm I missing something obvious here?

gdr39
  • 31
  • 8
  • `$newDate = date("Ymd", strtotime($test_date));` is all you need to do – RiggsFolly Jul 02 '18 at 15:23
  • Actually, are you using sensible date formats or American date formats – RiggsFolly Jul 02 '18 at 15:24
  • 1
    _Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed._ – AbraCadaver Jul 02 '18 at 15:25
  • @RiggsFollythats still gives 'Ydm', i'm guessing American if using / – gdr39 Jul 02 '18 at 15:28

1 Answers1

0

Looks like it's being parsed 'wrongly' because it's not explicitly stated what the source format is, using DateTime objects, you can do (not tested):

$result = substr($test_date, 0, 10);
$dateTime = DateTime::createFromFormat('d/m/Y', $result);
$newDate = $dateTime->format('Y-m-d');
echo $newDate;
martincarlin87
  • 10,848
  • 24
  • 98
  • 145
  • That worked, so you have to define the current format? – gdr39 Jul 02 '18 at 15:30
  • being explicit helps to avoid nasty surprises, otherwise you are leaving it to something internal to decide for you, I believe it tends to default to American format but might depend on the separator as mentioned by @AbraCadaver, I'd have to look it up. – martincarlin87 Jul 02 '18 at 21:53