Krajee

Date Control

Thankful to Krajee! BUY A COFFEEor to get more out of us.

The Date Control module allows controlling date formats of attributes separately for View and Model for Yii Framework 2.0. It allows you to set a separate format for saving dates to database and a separate format for display to users in your forms. It includes support out of the box for the enhanced DatePicker, DateTimePicker, and TimePicker widgets from yii2-widgets. In addition, you could configure any other date picker widget to be used with this module. With release 1.2.0, this module has various enhancements. It includes a separate DateFormatter library to manipulate dates in javascript using PHP DateTime formats. It does not require Intl extension for formatting nor the PHP 64 bit, and supports all date values (before 1970 and after 2037). It also includes preconfigured translations for most common languages (locales) and works well with kartik\widgets\DatePicker and kartik\widgets\DatePicker. This release tightens and enhances the DateControl integration with kartik\widgets\DatePicker, by allowing keyboard manipulation of dates. However, it is recommended to use the extension with ajaxConversion set to true if you need seamless integration with PHP DateTime functions like timezone support.

Important

  • Version 1.5.0 has BC breaking changes. This release now adds supports for both ICU and PHP date format patterns. By default the format will be parsed as a ICU date pattern. In order to pass a PHP Date format - prepend your format pattern with the string php:.

  • Version 1.9.5 has BC breaking changes. A new property widgetOptions is available. This will replace the options property for the scenario when autoWidget or widgetClass is set.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

DateControl supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the DateControl::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set DateControl::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x)

  • To use with bootstrap 4 library - you can set DateControl::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 library - you can set DateControl::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']). To set this up, add this section of code to your application params configuration file (e.g. config/params.php):

'params' => [
    'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions
    // other settings
    // 'adminEmail' => 'admin@example.com'
]

If DateControl::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (DateControl::bsVersion property) will override the Yii::$app->params['bsVersion']. If DateControl::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, DateControl::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency


You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap5": "@dev"

To install yiisoft/yii2-bootstrap4, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap4": "@dev"

To install yiisoft/yii2-bootstrap, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap": "@dev"

Override Bootstrap CSS/JS


The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

  • yii\bootstrap\BootstrapAsset and/or yii\bootstrap\BootstrapPluginAsset for bootstrap 3.x (bsVersion = 3 setting)

  • yii\bootstrap4\BootstrapAsset and/or yii\bootstrap4\BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

  • yii\bootstrap5\BootstrapAsset and/or yii\bootstrap5\BootstrapPluginAsset for bootstrap 5.x (bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

  • Global Override: Set Yii::$app->params['bsDependencyEnabled'] to false in your Yii 2 application config params.php. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

    'params' => [
        'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions
        // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets
        //
        // other params settings below
        // 'bsVersion' => '5.x',
        // 'adminEmail' => 'admin@example.com'
    ]
    
  • Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

    // ...
    'components' => [
        'assetManager' => [
            'bundles' => [
                'kartik\form\ActiveFormAsset' => [
                    'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle
                ],
            ],
        ],
    ],
    

Note

When setting bsDependencyEnabled to false, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap


Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x.

  • Option 1: Font CSS version of Font Awesome:

    <!-- on your view layout file HEAD section -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    
  • Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

    <!-- on your view layout file HEAD section -->
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
    

    Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

    // on your view layout file
    use kartik\icons\FontAwesomeAsset;
    FontAwesomeAsset::register($this);
    

The yii2-datecontrol extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-datecontrol via composer package manager. Either run:

$ php composer.phar require kartik-v/yii2-datecontrol "dev-master"

or add:

"kartik-v/yii2-datecontrol": "dev-master"

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

When working with the great Yii Framework, one of the most common observations I had was the need to have a proper control on the date settings. The date settings for each Yii application, are unique to each application and region. Most Yii developers or users almost always need an option of displaying date and time in ONE specific format, but save them to database in ANOTHER format. So to summarize, the problem statement was:

  • Lack of a single configuration method to display date & times to user (or VIEW) in ONE format
  • Lack of a configuration method to save date & times in database (or MODEL) in ANOTHER format

Most existing Yii solutions try to overcome the above by setting the format in model->afterFind, present in view, then unformat it in model->setAttribues or model->beforeValidate. This was still an issue when had one many models and views in the application and changes in development cycle, had to be replicated in many places (more complex scenarios being multi-regional formats).

This module helps overcome this large gap by addressing all of these at the presentational level. The module enables one to configure the date and time settings separately for DISPLAY and SAVE. This can be setup either globally or individually at each DateControl widget level. And if this is not useful enough, it automatically enables any date/time picker widgets to be used in conjunction with this.

How this magic works, is that the extension just alters this at the presentational layer (VIEW). It automatically sets the base model input to hidden and displays a mirror input in the display format one has set. Then on each edit of the display input, the extension traps the change event, and overrwrites the hidden base model input as per the desired save format. The other good thing is, that the extension automatically triggers the javascript change event for the base model input as well. Thus all client model validations and other jquery events needed by Picker widgets are automatically triggered.

NOTE

All date and time formats used across this module follow one standard - i.e. PHP Date Time format strings. The extension automatically provides three widgets to display and control the date-time inputs.
View a complete demo.
Display Format Defaulting Rules

The rules for deriving the display format for each type (date, datetime, or time) is validated in the following sequence:

  1. if displayFormat is set in DateControl widget, it will be first used

  2. else if Yii::$app->params['dateControlDisplay'] is set, it will be next used

  3. else, the format as set in Module::displaySettings will be used from the DateControl Module

  4. else, the format as set in Yii::$app->formatter will be used


Save Format Defaulting Rules

The rules for deriving the save format for each type (date, datetime, or time) is validated in the following sequence:

  1. if saveFormat is set in DateControl widget, it will be first used

  2. else if Yii::$app->params['dateControlSave'] is set, it will be next used

  3. else, the format as set in Module::saveSettings will be used from the DateControl Module

  4. else, the format as set in Yii::$app->formatter will be used


Example setup in Yii::$app->params
use kartik\datecontrol\Module;
// other settings
'params' => [
    // format settings for displaying each date attribute (ICU format example)
    'dateControlDisplay' => [
        Module::FORMAT_DATE => 'dd-MM-yyyy',
        Module::FORMAT_TIME => 'hh:mm:ss a',
        Module::FORMAT_DATETIME => 'dd-MM-yyyy hh:mm:ss a', 
    ],
    
    // format settings for saving each date attribute (PHP format example)
    'dateControlSave' => [
        Module::FORMAT_DATE => 'php:U', // saves as unix timestamp
        Module::FORMAT_TIME => 'php:H:i:s',
        Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
    ]
]
The extension has been created as a module to enable access to global settings for your application. In addition, it allows you to read and format date times between client and server using PHP DateTime object. The DateControl widget uses ajax processing to convert display (view) format to model (save) format. The module must be named datecontrol as shown below:
'modules' => [
   'datecontrol' =>  [
        'class' => '\kartik\datecontrol\Module'
    ]
];
The module can take in the following parameters:
  • displaySettings: array, the format settings for displaying each date attribute (in the view). An associative array that need to be setup as $type => $format, where:

    • type: string, one of the following formats:

      • Module::FORMAT_DATE or 'date'.

      • Module::FORMAT_TIME or 'time'.

      • Module::FORMAT_DATETIME or 'datetime'.

    • format: string the PHP date format string

    The Yii::$app->params['dateControlDisplay'] setting will override this. If this is not set, the display settings will automatically be derived from Yii::$app->formatter based on the type setting in the DateControl widget.

  • saveSettings: array, the format settings for saving each date attribute (to the model). An associative array that need to be setup as $type => $format, where:

    • type: string, one of the following formats:

      • Module::FORMAT_DATE or 'date'.

      • Module::FORMAT_TIME or 'time'.

      • Module::FORMAT_DATETIME or 'datetime'.

    • format: string the PHP date format string. Set this to 'php:U' to save it as Unix timestamp.

    The Yii::$app->params['dateControlSave'] setting will override this. If this is not set, the display settings will automatically be derived from Yii::$app->formatter based on the type setting in the DateControl widget.

  • displayTimezone: string,the timezone for the displayed date. Must be one of the PHP DateTimeZone formats. If not set, no timezone setting will be applied for formatting. Note: Timezones will work only if ajaxConversion is set to true.

  • saveTimezone: string,the timezone for the saved date. Must be one of the PHP DateTimeZone formats. If not set, no timezone setting will be applied for formatting. Note: Timezones will work only if ajaxConversion is set to true.

  • autoWidget: boolean, whether to automatically use a preset widget from \kartik\widgets based on $type. The following widgets will be automatically set for the formats:

    • \kartik\widgets\DatePicker for Module::FORMAT_DATE

    • \kartik\widgets\TimePicker for Module::FORMAT_TIME

    • \kartik\widgets\DateTimePicker for Module::FORMAT_DATETIME

    If this is not set, it will default to true.

  • widgetSettings: array, the widget settings that will be used to render the date input. NOTE: If autoWidget is true, this will be auto-generated, as explained above. An associative array that need to be setup as $type => $settings, where:

    • type: string, one of the following formats:

      • Module::FORMAT_DATE or 'date'.

      • Module::FORMAT_TIME or 'time'.

      • Module::FORMAT_DATETIME or 'datetime'.

    • settings: array which consists of these keys:

      • class: string the widget class name for the input widget that will render the date input.

      • options: array the HTML attributes for the input widget

  • convertAction: string, the route/action to convert the date as per the saveFormat in DateControl widget. Defaults to '/datecontrol/parse/convert'

  • ajaxConversion: boolean, whether to use ajax based date conversion from display to save formats. If set to false, the plugin will use php-date-formatter.js to convert to the set formats using client side validation. Defaults to true.

Usage

use \kartik\datecontrol\Module;
// other settings
'modules' => [
   'datecontrol' =>  [
        'class' => 'kartik\datecontrol\Module',

        // format settings for displaying each date attribute (ICU format example)
        'displaySettings' => [
            Module::FORMAT_DATE => 'dd-MM-yyyy',
            Module::FORMAT_TIME => 'hh:mm:ss a',
            Module::FORMAT_DATETIME => 'dd-MM-yyyy hh:mm:ss a', 
        ],
        
        // format settings for saving each date attribute (PHP format example)
        'saveSettings' => [
            Module::FORMAT_DATE => 'php:U', // saves as unix timestamp
            Module::FORMAT_TIME => 'php:H:i:s',
            Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
        ],

        // set your display timezone
        'displayTimezone' => 'Asia/Kolkata',

        // set your timezone for date saved to db
        'saveTimezone' => 'UTC',
        
        // automatically use kartik\widgets for each of the above formats
        'autoWidget' => true,

        // default settings for each widget from kartik\widgets used when autoWidget is true
        'autoWidgetSettings' => [
            Module::FORMAT_DATE => ['type'=>2, 'pluginOptions'=>['autoclose'=>true]], // example
            Module::FORMAT_DATETIME => [], // setup if needed
            Module::FORMAT_TIME => [], // setup if needed
        ],
        
        // custom widget settings that will be used to render the date input instead of kartik\widgets,
        // this will be used when autoWidget is set to false at module or widget level.
        'widgetSettings' => [
            Module::FORMAT_DATE => [
                'class' => 'yii\jui\DatePicker', // example
                'options' => [
                    'dateFormat' => 'php:d-M-Y',
                    'options' => ['class'=>'form-control'],
                ]
            ]
        ]
        // other settings
    ]
]
You could set a few configuration options through the Yii::$app->params. This is typically set through your Yii configuration file (e.g. main.php). The settings in params will override whatever you have setup at the module level. The difference in usage of params vs module is that the Yii params gives you an alternative option and also helps override settings at runtime. You can setup the following parameters in Yii::$app->params:
  • dateControlDisplay: array, the format settings for displaying each date attribute (in the view). An associative array that need to be setup as $type => $format, where:

    • type: string, one of the following formats:

      • Module::FORMAT_DATE or 'date'.

      • Module::FORMAT_TIME or 'time'.

      • Module::FORMAT_DATETIME or 'datetime'.

    • format: string the PHP date format string

  • dateControlSave: array, the format settings for saving each date attribute (to the model). An associative array that need to be setup as $type => $format, where:

    • type: string, one of the following formats:

      • Module::FORMAT_DATE or 'date'.

      • Module::FORMAT_TIME or 'time'.

      • Module::FORMAT_DATETIME or 'datetime'.

    • format: string the PHP date format string. Set this to 'php:U' to save it as Unix timestamp.

  • dateControlDisplayTimezone: string,the timezone for the displayed date. Must be one of the PHP DateTimeZone formats. If not set, no timezone setting will be applied for formatting. Note: Timezones will work only if ajaxConversion is set to true.

  • dateControlSaveTimezone: string,the timezone for the saved date. Must be one of the PHP DateTimeZone formats. If not set, no timezone setting will be applied for formatting. Note: Timezones will work only if ajaxConversion is set to true.

The DateControl widget allows you to render a date controlled input in each view. It uses the global settings from the module wherever available. You can override these settings at the widget/view level. The widget allows you to setup the following properties:
  • bsVersion: string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.

    • To use with Bootstrap library - you can set this to any string starting with 3 (e.g. 3 or 3.3.7 or 4.x / 3.x)

    • To use with bootstrap 4 - you can set this to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

    • To use with bootstrap 5 - you can set this to any string starting with 4 (e.g. 5 or 5.1.0 or 5.x)

  • bsColCssPrefixes: array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface. If not set will default to:.

    [
       3 => [
          self::SIZE_X_SMALL => 'col-xs-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-lg-',
          self::SIZE_XX_LARGE => 'col-lg-',
       ],
       4 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xl-',
       ],
       5 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xxl-',
       ],
    ];
    
  • language: string, the language code used for rendering the dates. This will use the language relatedconfiguration date setting formats, from the configuration in the locales folder of this extension. When autoWidget is true, this will automatically set the languages for DatePicker, DateTimePicker, or TimePicker widgets.

  • type: string, data type to use for the displayed date control. Should be one of the following values:

    • DateControl::FORMAT_DATE or 'date'.

    • DateControl::FORMAT_TIME or 'time'.

    • DateControl::FORMAT_DATETIME or 'datetime'.

  • displayFormat: string,the format string for displaying the date (in the view). If not set, will automatically derive this based on displaySettings in the Module based on the type setting. Note the format can be passed as a ICU format OR a PHP datetime format, exactly as in yii\i18n\Formatter. If you are passing a PHP format, prefix the format with the pattern php:.

  • saveFormat: string, the format string for saving the date (to the model). If not set, will automatically derive this based on saveSettings in the Module based on the type setting. Note the format can be passed as a ICU format OR a PHP datetime format, exactly as in yii\i18n\Formatter. If you are passing a PHP format, prefix the format with the pattern php:.

  • displayTimezone: string,the timezone for the displayed date. Must be one of the PHP DateTimeZone formats. If not set, no timezone setting will be applied for formatting. Note: Timezones will work only if ajaxConversion is set to true.

  • saveTimezone: string,the timezone for the saved date. Must be one of the PHP DateTimeZone formats. If not set, no timezone setting will be applied for formatting. Note: Timezones will work only if ajaxConversion is set to true.

  • autoWidget: boolean, whether to automatically use a preset widget from \kartik\widgets based on $type. This will override the setting at the Module level. The following widgets will be automatically set for the formats:

    • \kartik\widgets\DatePicker for Module::FORMAT_DATE

    • \kartik\widgets\TimePicker for Module::FORMAT_TIME

    • \kartik\widgets\DateTimePicker for Module::FORMAT_DATETIME

  • widgetClass: string, any custom widget class to use. Will only be used if autoWidget is set to false. NOTE: A normal text input will be generated, if this is not set and autoWidget is false

  • widgetOptions: string, the configuration options for the widget which will be parsed only in one of the following cases:

    • when autoWidget is true and this corresponds to widget settings for DatePicker, TimePicker, or DateTimePicker based on the type setting, OR

    • when autoWidget is false and widgetClass is set and this allows to set the configuration options for the particular widget class.

  • options: string, the HTML attributes for the display input. This property is applicable and parsed only if autoWidget is false and widgetClass is NOT set or empty.

  • disabled: boolean whether the input widget is to be entirely disabled. Defaults to false. Note this will disable properly if you use normal HTML inputs OR have autoWidget property set to true. For other custom widgets, this will be applied only if the widget has a disabled property.

  • readonly: boolean whether the input widget is to be entirely readonly. Defaults to false. Note this will set to readonly properly if you use normal HTML inputs OR have autoWidget property set to true. For other custom widgets, this will be applied only if the widget has a readonly property.

  • saveOptions: string, the HTML attributes for the base model input that will be saved typically to database. The following special options are recognized:

    • type: string whether to generate a hidden or text input. Defaults to hidden.

    • label: string any label to be placed before the input. Will be only displayed if type is set to text.

  • ajaxConversion: boolean, whether to use ajax based date conversion from display to save formats. If set to false, the plugin will use php-date-formatter.js to convert to the set formats using client side validation. Defaults to true and is overridden by the value set at Module level.

  • asyncRequest: boolean, whether to fire an asynchronous ajax request (applicable when ajaxConversion is set to true). Defaults to true. You can set this to false for cases, where you need this to be fired synchronously. For example, when using this widget as a filter in \kartik\grid\GridView, with a PJAX enabled grid.

  • pluginOptions: array, the jQuery plugin options for the datecontrol plugin. The following options can be setup:

    • dateSettings: array, This property allows you to configure the terms used for short/long days and months, and the meridiem. This is defaulted to:

      {
          longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
          shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
          shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
          longMonths: ['January', 'February', 'March', 'April', 'May', 'June',
              'July', 'August', 'September', 'October', 'November', 'December'],
          meridiem: ['AM', 'PM']
      }
      

      This property will be autogenerated from the locales configuration based on the language setting. You can override this at runtime.

For the examples below, the displaySettings and saveSettings are set to the following at the module configuration level :

 // format settings for displaying each date attribute (ICU format example)
'displaySettings' => [
    Module::FORMAT_DATE => 'dd-MM-yyyy',
    Module::FORMAT_TIME => 'hh:mm:ss a',
    Module::FORMAT_DATETIME => 'dd-MM-yyyy hh:mm:ss a', 
],

// format settings for saving each date attribute (PHP format example)
'saveSettings' => [
    Module::FORMAT_DATE => 'php:U', // saves as unix timestamp
    Module::FORMAT_TIME => 'php:H:i:s',
    Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
],
View a complete demo.
Input saved as:
Use DatePicker input with ActiveForm and model validation enabled (without ajax conversion). The saved value is displayed for the demo.

Input saved as:
Use a DateTimePicker input with ActiveForm and model validation enabled. The saved value is displayed for the demo.

Input saved as:
Use a TimePicker input with ActiveForm and model validation enabled. The saved value is displayed for the demo.

Input saved as:
Use a plain text input with no model, no ActiveField validation with both custom display and save formats. The saved value is displayed for the demo.

Input saved as:
Use a custom widget, with custom format (ICU notation), and widget options - for example the yii\widgets\MaskedInput.
Input saved as:
Use different timezones. Timezone for display as Pacific/Chatham and for save as UTC.
A disabled DateControl widget setup for time format using kartik\widgets\TimePicker.
use kartik\datecontrol\DateControl;

// Use DatePicker input with ActiveForm and model validation enabled (without ajax conversion). 
echo $form->field($model, 'test_date')->widget(DateControl::classname(), [
    'type'=>DateControl::FORMAT_DATE,
    'ajaxConversion'=>false,
    'widgetOptions' => [
        'pluginOptions' => [
            'autoclose' => true
        ]
    ]
]);

// Use a DateTimePicker input with ActiveForm and model validation enabled. 
echo $form->field($model, 'datetime_1')->widget(DateControl::classname(), [
    'type'=>DateControl::FORMAT_DATETIME
]);

// Use a TimePicker input with ActiveForm and model validation enabled. 
echo $form->field($model, 'datetime_2')->widget(DateControl::classname(), [
    'type'=>DateControl::FORMAT_TIME
]);

// Use a plain text input with no model, no ActiveField validation with both custom display and save formats.
echo DateControl::widget([
    'name'=>'kartik-date', 
    'value'=>time(),
    'type'=>DateControl::FORMAT_TIME,
    'autoWidget'=>false,
    'displayFormat' => 'php:D, d-M-Y H:i:s A'
    'saveFormat' => 'php:U'
]);

//  Use a custom widget, with custom format (ICU notation), and widget options - for example the yii\widgets\MaskedInput.
echo $form->field($model, 'to_date')->widget(DateControl::classname(), [
    'displayFormat' => 'dd/MM/yyyy',
    'autoWidget' => false,
    'widgetClass' => 'yii\widgets\MaskedInput',
    'widgetOptions' => [
        'mask' => '99/99/9999'
    ],
]);

// Use different timezones for display (Pacific/Chatham) and save (UTC)
echo DateControl::widget([
    'name'=>'kartik-date-3', 
    'value'=>time(),
    'type'=>DateControl::FORMAT_DATETIME,
    'displayTimezone'=>'Pacific/Chatham',
    'saveTimezone'=>'UTC'
]);

// A disabled DateControl widget setup for time format using `kartik\widgets\TimePicker`.
echo DateControl::widget([
    'name'=>'kartik-date-3', 
    'value'=>date('H:i:s'),
    'type'=>DateControl::FORMAT_TIME,
    'disabled'=>true
]);

yii2-datecontrol is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017