kodfire
kodfire

Reputation: 1783

Laravel - dateformat validation not working as expected

My code:

$data['from'] = '2020-03-20 20:30:00';
$data['to'] = '2020-03-21 00:45:00';
$validity = \Validator::make($data, [
    'from' => ['date_format:Y-m-d H:i:s'],
    'to' => ['date_format:Y-m-d H:i:s']
]);

// This if gets true, and the error message is:

The to does not match the format Y-m-d H:i:s

if($validity->fails()) {
    dd($validity->errors());
}

and amazingly when I change 00:45:00 to 01:45:00 it doesn't get inside that if. How can I fix it?

Upvotes: 1

Views: 794

Answers (2)

Bharat Rawat
Bharat Rawat

Reputation: 42

Try

$validity = \Validator::make($data, [
    'from' => 'date_format:Y-m-d H:i:s',
    'to' => 'date_format:Y-m-d H:i:s'
]);

Upvotes: 0

apokryfos
apokryfos

Reputation: 40653

Since your locale is set up to be Asia/Tehran the time 2020-03-21 00:45:00 is actually not valid. According to https://www.timeanddate.com/time/change/iran/tehran:

Saturday, 21 March 2020, 00:00:00 clocks are turned forward 1 hour to Saturday, 21 March 2020, 01:00:00 local daylight time instead.

This means that times between 00:00:00 and 01:00:00 never occur. Since the Laravel date validator internally uses PHP's date parsing then that parsing fails and the error is raised. If you want to check only if a date is a given format ignoring any daylight savings quirks then you can use date_default_timezone_set to temporarily set the locale to one that does not observe daylight savings.

Upvotes: 5

Related Questions