简体   繁体   中英

Yii2: How to compare two dates?

In my form

<?= $form->field($model, 'check_in')->input('date', ['required' => false])->label(false); ?>
<?= $form->field($model, 'check_out')->input('date', ['required' => false])->label(false); ?>

there are two fields check_in and check_out i need to validate this two fields, check_out should not be smaller than check_in date how to do this?

You could simply use compare validator :

// first validate date format
[['check_in', 'check_out'], 'date'],
// then compare attributes
['check_out', 'compare', 'compareAttribute' => 'check_in', 'operator' => '>'],

Read more about compare validator .

You can use the compare validator in your model's rules function:

['check_in', 'compare', 'compareAttribute' => 'check_out', 'operator' => '<='],

This will resolve to $model->check_in <= $model->check_out

Comparing date values has been available on Yii2:

['checkIn', 'date', 'timestampAttribute' => 'checkIn'],
['checkOut', 'date', 'timestampAttribute' => 'checkOut'],
['checkOut', 'compare', 'compareAttribute' => 'checkIn', 'operator' => '<', 'enableClientValidation' => false],

You can research more at the resource linked here Comparing date value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM