0

I am having a variable which holds date as string like March 21, 2015,so I need to check whether it is a valid in php.I tries to check using

$date = 'July 20 2018'; echo date('d/m/Y', strtotime($date));

But it showing error and also tried

if (DateTime::createFromFormat('Y-m-d G:i:s', $myString) !== FALSE) { //valid date }

Getting error 2nd parameter must be string. Please anybody can help me !

Sajith Sajan
  • 119
  • 7
  • So, `$myString` is not a string. Find a value which is __string__. – u_mulder May 05 '18 at 11:52
  • Also, in your call to `createFromFormat()`, `'Y-m-d G:i:s'` doesn't match to your format. – Syscall May 05 '18 at 11:56
  • 2
    Possible duplicate of [Correctly determine if date string is a valid date in that format](https://stackoverflow.com/questions/19271381/correctly-determine-if-date-string-is-a-valid-date-in-that-format) – Pradeep May 05 '18 at 11:57
  • If this answer is right for you, please mark answer as "accepted". –  May 05 '18 at 12:08

1 Answers1

0

strtotime will parse the date string to a number: please refer to this.

so the returned value from strtotime cannot be passed to createfromFromat as the second parameter.

You can use the following code to verify the date

$date = DateTime::createFromFormat('July 25 2010', 'F j Y');
return $date && ($date->format('F j Y') === 'July 25 2010');
Rumit Patel
  • 8,830
  • 18
  • 51
  • 70
Ryon
  • 1
  • 1