Home > Article > Backend Development > Yii2 super easy-to-use date component and time component_php skills
Date components and time components are essential in daily development. Today we will talk about the super easy-to-use time component in yii2, which will also save everyone the trouble of looking for js plug-ins.
Before sharing, let’s preview the effect to see how it works well.
Of course, whether it is useful or not depends on your own feelings. You can’t feel it just by looking at the picture above. Let me tell you some good news, these two plug-ins have been integrated with yii2, and they are very simple to use.
Regarding the date component and time component, the former is of type date('Y-m-d') and the latter is of type date('Y-m-d H:i:s'). Needless to say, there is no need to say more.
Let’s first take a look at the time component extension
Since it is an extension, the first step is of course installation.
composer require kartik-v/yii2-widget-datetimepicker "*"
After installation, if your form is generated using ActiveForm, you can refer to the following code
use kartik\datetime\DateTimePicker; <?= $form->field($model, 'created_at')->widget(DateTimePicker::classname(), [ 'options' => ['placeholder' => ''], 'pluginOptions' => [ 'autoclose' => true, 'todayHighlight' => true, ] ]); ?>
Some students who don’t like to use ActiveForm to generate forms need to refer to the following usage
use kartik\datetime\DateTimePicker; echo '<label>时间</label>'; echo DateTimePicker::widget([ 'name' => 'Article[created_at]', 'options' => ['placeholder' => ''], //注意,该方法更新的时候你需要指定value值 'value' => '2016-05-03 22:10:10', 'pluginOptions' => [ 'autoclose' => true, 'format' => 'yyyy-mm-dd HH:ii:ss', 'todayHighlight' => true ] ]);
至于哪个方便,不言而喻。
整个安装过程确实很简单,我们接下来以同样的方式进行安装日期组件。
composer require kartik-v/yii2-widget-datepicker "@dev"
安装好了后我们开始使用日期组件
use kartik\date\DatePicker; <?php echo DatePicker::widget([ 'name' => 'Article[created_at]', 'options' => ['placeholder' => '...'], //value值更新的时候需要加上 'value' => '2016-05-03', 'pluginOptions' => [ 'autoclose' => true, 'format' => 'yyyy-mm-dd', 'todayHighlight' => true, ] ]); ?>
看了上面的代码,想必有同学已经猜到针对ActiveForm生成的日期组件的用法了。没错,就那么用,si不si很简单。
<?= $form->field($model, 'created_at')->widget(DatePicker::classname(), [ 'options' => ['placeholder' => ''], 'pluginOptions' => [ 'autoclose' => true, 'todayHighlight' => true, 'format' => 'yyyy-mm-dd', ] ]); ?>
当然,上面的时间格式都是可以调整的,但是,日期组件,既然是日期,肯定也就只支持ymd三种类型的参数,不然跟时间组件又有啥差别。
有些小伙伴说为啥自己的是英文的,用起来很不方便呀,我想反问一句,你的项目是不是没配置语言是中文?还没配置的同学只需要在你的配置文件里面加上 'language'=>'zh-CN', 即可。
最后,我们看看最终的效果图。