Shehary
Shehary

Reputation: 9992

While importing CSV getting this error DateTime::__construct(): Failed to parse time string

I'm importing data from CSV file into database through HTML form, sometime it works fine and sometime it throws an error DateTime::__construct(): Failed to parse time string (23/06/2015 12:00)

Following is the code where it throws error

$DepDate = $emapData['1']; //Format is 23/06/2015 12:00
$depdatetime = new DateTime($DepDate); //Here it throws error
$date_depart = $depdatetime->format('Y-m-d');
$time_depart = $depdatetime->format('H:i');

Note: I was using explode and it worked fine but i wana use new DateTime();

Upvotes: 1

Views: 248

Answers (2)

Eric J.
Eric J.

Reputation: 150108

DateTime() does not understand the format you are providing. It can accept a range of formats including ISO8601, but not 23/06/2015 12:00. Note @MarkBaker's comment that the / separator you are using implies US date formatting where the first position is the month, and there is no month 23.

If you cannot change the /, you can use the method DateTime::createFromFormat to specify a format matching your actual data format.

Upvotes: 1

Anonymous
Anonymous

Reputation: 12090

You can use DateTime::createFromFormat() and explicitly set the format of the date in the string. Alternatively, you can tell PHP to guess the format: new DateTime('@'.strtotime($date)). This, however, is error prone.

Upvotes: 0

Related Questions