Frees
Frees

Reputation: 149

PHP DateTime createFormat from invalid date

Hi I want to create DateTime object from date 1989-06-31. As you can see this date has bad count of days(June can't have 31 days). But calling this

$semi_valid_date = "1989-06-31";
$semi_valid_datetime = DateTime::createFromFormat('Y-m-d',$semi_valid_date);
$valid_date = $semi_valid_datetime->format('Y-m-d');

will store to $valid_date date 1989-07-01.

Is it possible to throw error, when month has more days, than it can have?

Upvotes: 1

Views: 80

Answers (1)

John Conde
John Conde

Reputation: 219804

Use checkdate() to validate the date before attempting to use it:

var_dump(checkdate(6, 31, 1989));
// bool(false)

var_dump(checkdate(6, 30, 1989));
// bool(true)

See it in action

Upvotes: 1

Related Questions