Datetimepicker: выберите дату и время

Defining Buttons

In order to facilitate defining buttons, a new class was defined. its properties will be used to create buttons automatically. in addition, defines a few handy predefined functionalities (at the moment -button, -button)


accepts following options:

Button Options

var options = {
	name: '',
	label: '',
	className: '',
	title:'',
	placeholder: null,
	onClick: function(dateTimePickerInstance){},
	show: function(dateTimePickerInstance){} // can also be true or false
};

these options will translate into:

will be evaluated before putting the button on the page. it can be any value which could be interpreted as boolean, or it could define a function, which should return or . if the value is evaluated to , then the button will not appear in the widget.

it’s possible to change a button’s settings using this function. but they won’t take effect if they buttons are already drawn, unless buttons are redrawn with .

or

currently, 2 default buttons are defined in this class:

  1. button will set date/time values to current moment.
  2. button will set the time to of selected day. by default it’s only available (i.e. n) if selection is allowed.
  3. button will set the time to of selected day. by default it’s only available (i.e. n) if selection is allowed.
$.DateTimePicker.DefaultButtons = {
	now: new $.DateTimePicker.Button({
		name: 'now',
		label: 'Now',
		onClick: function (picker){
			if(picker instanceof $.DateTimePicker)
			{
				let current = moment();
				picker.events.set.call(picker, current, null);
				picker.$el.change();
			}
		}
	}),
    dayBegin: new $.DateTimePicker.Button({
        name: 'day_begin',
        label: 'Day Begin',
        onClick: function (picker){
            if(picker instanceof $.DateTimePicker)
            {
                let current = moment(picker.$el.val());
                current.set({
                    hour: ,
                    minute: ,
                    second: ,
                    millisecond: 
                });
                picker.events.set.call(picker, current, null);
                picker.$el.change();
            }
        },
        show: function(picker){
            if (picker instanceof $.DateTimePicker)
            {
                return (picker.allows("time") && picker.viewpoint === 'days');
            }
            else
            {
                return false;
            }
        }
    }),
    dayEnd: new $.DateTimePicker.Button({
        name: 'day_end',
        label: 'Day End',
        onClick: function (picker){
            if(picker instanceof $.DateTimePicker)
            {
                let current = moment(picker.$el.val());
                current.set({
                    hour: 23,
                    minute: 59,
                    second: 59,
                    millisecond: 999
                });
                picker.events.set.call(picker, current, null);
                picker.$el.change();
            }
        },
        show: function(picker){
            if (picker instanceof $.DateTimePicker)
            {
                return (picker.allows("time") && picker.viewpoint === 'days');
            }
            else
            {
                return false;
            }
        }
    })
};

or

Markup

Format as component.

<divclass="input-append date"id="datetimepicker"data-date="12-02-2012"data-date-format="dd-mm-yyyy"><inputclass="span2"size="16"type="text"value="12-02-2012"><spanclass="add-on"><iclass="icon-th"><i></span></div>

Format as component with reset button to clear the input field.

<divclass="input-append date"id="datetimepicker"data-date="12-02-2012"data-date-format="dd-mm-yyyy"><inputclass="span2"size="16"type="text"value="12-02-2012"><spanclass="add-on"><iclass="icon-remove"><i></span><spanclass="add-on"><iclass="icon-th"><i></span></div>

Keyboard support

The datetimepicker includes some keyboard navigation:

By themselves, left/right will move backward/forward one day, up/down will move back/forward one week.

With the shift key, up/left will move backward one month, down/right will move forward one month.

With the ctrl key, up/left will move backward one year, down/right will move forward oone year.

Shift+ctrl behaves the same as ctrl — that is, it does not change both month and year simultaneously, only the year.

The escape key can be used to hide and re-show the datetimepicker; this is necessary if the user wants to manually edit the value.

When the picker is visible, enter will simply hide it. When the picker is not visible, enter will have normal effects — submitting the current form, etc.

调用方法

设置时间格式: 选项

<input type="text" value="2015-02-15 21:05" id="datetimepicker" class="am-form-field">
$('#datetimepicker').datetimepicker({
  format: 'yyyy-mm-dd hh:ii'
});

也可以通过 来设置时间格式

<input type="text" value="2015-02-14 21:05" id="datetimepicker" data-date-format="yyyy-mm-dd hh:ii">
$('#datetimepicker').datetimepicker();

结合 Amaze UI 组件

结合 Amaze UI Class 来实现组件样式,其中 Class 、、 都在原 JS 中有引用,使用时务必加上。

<div class="am-input-group date" id="datetimepicker" data-date="12-02-2012" data-date-format="dd-mm-yyyy">
  <input size="16" type="text" value="2015-02-14 14:45" class="am-form-field" readonly>
  <span class="am-input-group-label add-on"><i class="icon-th am-icon-calendar"></i></span>
</div>
$('#datetimepicker').datetimepicker();

内联调用:

<div id="datetimepicker"></div>
$('#datetimepicker').datetimepicker();

Keyboard support

The datetimepicker includes some keyboard navigation:

up, down, left, right arrow keys

By themselves, left/right will move backward/forward one day, up/down will move back/forward one week.

With the shift key, up/left will move backward one month, down/right will move forward one month.


With the ctrl key, up/left will move backward one year, down/right will move forward oone year.

Shift+ctrl behaves the same as ctrl — that is, it does not change both month and year simultaneously, only the year.

escape

The escape key can be used to hide and re-show the datetimepicker; this is necessary if the user wants to manually edit the value.

enter

When the picker is visible, enter will simply hide it. When the picker is not visible, enter will have normal effects — submitting the current form, etc.

Full options list

Name default Descr Ex.
false Initializing plugin occurs only when the user interacts. Greatly accelerates plugin work with a large number of fields
‘body’ Attach datetimepicker to this element, which can be either a selector or a DOM/JQuery element
null Current value datetimepicker. If it is set, ignored input.value
en Language i18nar — Arabic az — Azerbaijanian (Azeri) bg — Bulgarian bs — Bosanski ca — Català ch — Simplified Chinese cs — Čeština da — Dansk de — German el — Ελληνικά en — English en-GB — English (British) es — Spanish et — «Eesti» eu — Euskara fa — Persian fi — Finnish (Suomi) fr — French gl — Galego he — Hebrew (עברית) hr — Hrvatski hu — Hungarian id — Indonesian it — Italian ja — Japanese ko — Korean (한국어) kr — Korean lt — Lithuanian (lietuvių) lv — Latvian (Latviešu) mk — Macedonian (Македонски) mn — Mongolian (Монгол) nl — Dutch no — Norwegian pl — Polish pt — Portuguese pt-BR — Português(Brasil) ro — Romanian ru — Russian se — Swedish sk — Slovenčina sl — Slovenščina sq — Albanian (Shqip) sr — Serbian Cyrillic (Српски) sr-YU — Serbian (Srpski) sv — Svenska th — Thai tr — Turkish uk — Ukrainian vi — Vietnamese zh — Simplified Chinese (简体中文) zh-TW — Traditional Chinese (繁體中文)
Y/m/d H:i Format datetime. More Also there is a special type of
Y/m/d Format date for minDate and maxDate
H:i Similarly, formatDate . But for minTime and maxTime
60 Step time
true
true Verify datetime value from input, when losing focus. If value is not valid datetime, then to value inserts the current datetime
true
true
false Show week number
‘default’ Setting a color scheme. Now only supported default and dark theme
false
false
false calendar set date use starDate
false if input value is empty, calendar set date use defaultDate
false if input value is empty, timepicker set time use defaultTime
false
false
[]
false Use mask for input. true — automatically generates a mask on the field ‘format’, Digit from 0 to 9, set the highest possible digit for the value. For example: the first digit of hours can not be greater than 2, and the first digit of the minutes can not be greater than 5
{mask:'9999/19/39',format:'Y/m/d'}
{mask:true,format:'Y/m/d'} // automatically generate a mask 9999/99/99
{mask:'29:59',format:'H:i'} //
{mask:true,format:'H:i'} //automatically generate a mask 99:99
false
Year offset for Buddhist era
false
true Show button «Go To Today»
true Highlight the current date even if the input is empty
false Allow field to be empty even with the option in true
true
function(){}
function(current_time,$input){}
function(current_time,$input){}
function(current_time,$input){}
function(current_time,$input){}
function(current_time,$input){}
function(current_time,$input){}
function(current_time,$input){} trigger after construct calendar and timepicker
withoutCopyright true
false
false
1950 Start value for fast Year selector
2050 End value for fast Year selector
round Round time in timepicker, possible values: round, ceil, floor

Star week DatePicker. Default Sunday — 0.

Monday — 1 …

className
[]
[]

Disbale all dates in list

[]

Allow all dates in list

[]

Use Regex to check dates

[]

Disable days listed by index

id
style
ownerDocument document The ownerDocument object for the datetimepicker to properly attach events and calc position (iframe support).
contentWindow window The contentWindow object that contains the datetimepicker to properly attach events (iframe support).

Keyboard Shortcuts

Key Action
Closes the Date Time Picker without selecting a date or time.
Closes the Date Time Picker without selecting a date or time.
Selects the current chosen year, month, date or time. In the date or time view the picker will return the select date and / or time.
Changes the view between date, month or year.
Navigates to the current day, month or year depending on which view is selected.
Navigates between days, months, years, hour or minutes depending on which view is selected.
Navigates between days, months, years, hour or minutes depending on which view is selected.
Navigates between days, months or years depending on which view is selected. If the time picker is visible will increase the hours or minutes depending of which has focus.
Navigates between days, months or years depending on which view is selected. If the time picker is visible will decrease the hours or minutes depending of which has focus.

I18N

The plugin supports i18n for the month and weekday names and the option. The default is English (‘en’); other available translations are avilable in the directory, simply include your desired locale after the plugin. To add more languages, simply add a key to , before calling . Example:

$.fn.datetimepicker.dates'en' = {
    days: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday",
    daysShort: "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
    daysMin: "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su",
    months: "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December",
    monthsShort: "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    today: "Today"
};

You can override the default date format in the language configuration with attribute. Example:

$.fn.datetimepicker.dates'pt-BR' = {
    format: 'dd/mm/yyyy'
};

Right-to-left languages may also include to make the calendar display appropriately.

If your browser (or those of your users) is displaying characters wrong, chances are the browser is loading the javascript file with a non-unicode encoding. Simply add to your tag:

<script type="text/javascript" src="uikit-datetimepicker.de.js" charset="UTF-8"></script>

Свойства, унаследованные от IControl

  Имя свойства Краткое описание
Align Свойство Align определяет выравнивание компонента в рамках содержащего его родительского компонента.
AllowDrag Свойство AllowDrag определяет возможность взять у компонента перетаскиваемый объект.
AllowDrop Свойство AllowDrop определяет, будет ли возможность у компонента принять перетаскиваемый объект.
Anchors Свойство Anchors возвращает настройки, определяющие в процентном соотношении изменение размеров текущего компонента при изменении размеров родительского компонента.
Brush Свойство Brush определяет кисть, используемую для заливки области компонента.
ClientHeight Свойство ClientHeight определяет высоту клиентской области компонента.
ClientWidth Свойство ClientWidth определяет ширину клиентской области компонента.
Color Свойство Color определяет цвет фона компонента.
Cursor Свойство Cursor определяет вид курсора, отображаемого при наведении курсора мыши на компонент, во время выполнения формы.
Enabled Свойство Enabled определяет доступность компонента для пользователя.
Focused Свойство Focused возвращает True, если фокус установлен на данном компоненте.
Font Свойство Font определяет параметры шрифта, используемого при отображении текста в компоненте.
Height Свойство Height определяет высоту компонента в пикселях.
HelpContext Свойство HelpContext определяет уникальный индекс раздела контекстно-зависимой справки для данного компонента.
Hint Свойство Hint определяет текст подсказки, появляющийся при задержке указателя мыши над компонентом.
HintTimeout Свойство HintTimeout определяет время отображения всплывающей подсказки.
Left Свойство Left определяет координату левого края компонента в пикселях.
Parent Свойство Parent определяет родительский компонент.
ParentColor Свойство ParentColor определяет, будет ли для компонента заимствован цвет родительского компонента.
ParentFont Свойство ParentFont определяет, будет ли для компонента использоваться шрифт родительского компонента.
ParentShowHint Свойство ParentShowHint определяет условие отображения всплывающей подсказки.
PopupMenu Свойство PopupMenu определяет контекстное меню, которое будет появляться при щелчке правой клавишей мыши на компоненте.
Scrolls Свойство Scrolls возвращает параметры полос прокрутки компонента.
ShowHint Свойство ShowHint определяет, будет ли показываться всплывающая подсказка при задержке курсора мыши над компонентом.
TabOrder Свойство TabOrder определяет позицию компонента в последовательности табуляции.
TabStop Свойство TabStop определяет признак необходимости компоненту получать фокус при нажатии кнопки «Tab».
Text Свойство Text определяет строку, идентифицирующую компонент для пользователя.
Top Свойство Top определяет координату верхнего края компонента в пикселях.
Visible Свойство Visible определяет видимость компонента во время выполнения формы.
Width Свойство Width определяет горизонтальный размер компонента в пикселях.

Mouse Wheel View Navigation

In order to make this plugin easier to set different part of date time, mouse wheel has been used to navigate through different views. Scroll up your mouse wheel to navigate to the decade year view. Scroll down will lead to the minute view.

Boolean. Default: false

Whether or not to enable navigating through different view mode using mouse wheel.

Boolean. Default: false

Whether or not to reverse the direction of scrolling. Default is scroll up to the decade view.

Integer. Default: 100

Time delays between the next respond to the wheel command, it controls the speed between switching in different views. Unit is in million seconds.

The recommended value for viewSelect option is 4 when this feature is enable. That means you can easily update any the value in every view. This option value is applied in the demo page.

Additional Options

The dialogs have a dark theme that can be set by calling

dialog.setThemeDark(true);

Set the accentColor to be used by the Dialog. The String version parses the color out using . The int version requires a ColorInt bytestring. It will explicitly set the color to fully opaque.


Set the text color for the OK or Cancel button. Behaves similar to

Shows a title at the top of the

Shows a title at the top of the instead of the day of the week

Set a custom text for the dialog Ok and Cancel labels. Can take a resourceId of a String. Works in both the DatePickerDialog and TimePickerDialog

Set the minimum valid date to be selected. Date values before this date will be deactivated

Set the maximum valid date to be selected. Date values after this date will be deactivated

Set the minimum valid time to be selected. Time values earlier in the day will be deactivated

Set the maximum valid time to be selected. Time values later in the day will be deactivated

You can pass in an array of . These values are the only valid selections in the picker. , and will further trim this list down. Try to specify Timepoints only up to the resolution of your picker (i.e. do not add seconds if the resolution of the picker is minutes).

You can pass in an array of . These values will not be available for selection. These take precedence over and . Be careful when using this without selectableTimes: rounding to a valid Timepoint is a very expensive operation if a lot of consecutive Timepoints are disabled. Try to specify Timepoints only up to the resolution of your picker (i.e. do not add seconds if the resolution of the picker is minutes).

Set the interval for selectable times in the TimePickerDialog. This is a convenience wrapper around . The interval for all three time components can be set independently. If you are not using the seconds / minutes picker, set the respective item to 60 for better performance.

You can pass a to the . The values in this list are the only acceptable dates for the picker. It takes precedence over and

The values in this are explicitly disabled (not selectable). This option can be used together with : in case there is a clash will take precedence over

You can pass a of days to highlight. They will be rendered in bold. You can tweak the color of the highlighted days by overwriting

Show the year picker first, rather than the month and day picker.

Both pickers can be passed a or which allows you to run code when either of these events occur.

tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
    @Override
    public void onCancel(DialogInterface dialogInterface) {
      Log.d("TimePicker", "Dialog was cancelled");
    }
});

Set whether the dialogs should vibrate the device when a selection is made. This defaults to .

Set whether the picker dismisses itself when the parent Activity is paused or whether it recreates itself when the Activity is resumed.

Allows the client to set a custom locale that will be used when generating various strings in the pickers. By default the current locale of the device will be used. Because the pickers will adapt to the Locale of the device by default you should only have to use this in very rare circumstances.

If set to will dismiss the picker when the user selects a date. This defaults to .

Allows you to enable or disable a seconds and minutes picker on the . Enabling the seconds picker, implies enabling the minutes picker. Disabling the minute picker will disable the seconds picker. The last applied setting will be used. By default and .

deprecated

Sets the used to represent time internally in the picker. Defaults to the current default Timezone of the device. This method has been deprecated: you should use the method which takes a Calendar set to the appropriate TimeZone.

Provide a custom implementation of DateRangeLimiter, giving you full control over which days are available for selection. This disables all of the other options that limit date selection.

Demo

The date and time picker can be used in two modes:

  • Analog Time Picker
  • Digital Time Picker

Code:

view model =
    DateTimePicker.dateTimePickerWithConfig
        { defaultDateTimeConfig | timePickerType = DateTimePicker.Config.Analog }
         class "my-datetimepicker" 
        model.state
        model.value

Code:

view model =
    DateTimePicker.dateTimePickerWithConfig
        { defaultDateTimeConfig | timePickerType = DateTimePicker.Config.Digital }
         class "my-datetimepicker" 
        model.state
        model.value

Date Picker

Just the date picker without the time.

Code:

type Msg = DateChange DateTimePicker.State (Maybe Date)

type alias Model = { value  Maybe Date, state  DateTimePicker.State }

view model =
    DateTimePicker.datePicker
        DateChange
         class "my-datepicker" 
        model.state
        model.value

Just the time picker without the date.

Code:

type Msg = TimeChange DateTimePicker.State (Maybe Date)

type alias Model = { value  Maybe Date, state  DateTimePicker.State }

view model =
    DateTimePicker.timePicker
        TimeChange
         class "my-timepicker" 
        model.state
        model.value

Date-formatting

The date-formatting functions featured in the DateTimePicker support the symbols listed below. Unsupported symbols will just be output as provided. To use the supported symbols literally, escape them with .

Character Description Return Value
Two digit representation of a year
Four digit representation of a year
Numeric representation of a month, with leading zeros
Numeric representation of a month, without leading zeros
A short textual representation of a month, three letters
A full textual representation of a month, such as January or March
Day of the month, 2 digits with leading zeros
Day of the month without leading zeros
A textual representation of a day, three letters
A full textual representation of the day of the week (lowercase ‘L’)
24-hour format of an hour without leading zeros
24-hour format of an hour with leading zeros
12-hour format of an hour without leading zeros
12-hour format of an hour with leading zeros
Lowercase Ante meridiem and Post meridiem
Uppercase Ante meridiem and Post meridiem
Minutes with leading zeros
Seconds, with leading zeros
Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT
Milliseconds since January 1 1970 00:00:00 GMT (Easily used to create a for example )
The suffix for the day of the month (as in 1st, 2nd, 23rd or 25th)

Usage with Ajax

After the DateTimePicker instance has been created, when using ajax to retrieve a new date, there are two methods that can be used to update the instance and correctly formatted the retrieved date. When loading or updating the date via the input elements attribute, by simply calling the method, the DateTimePicker will re-bind to its targets and correctly format the new date value.

dtp.refresh();

When it is required to loading or updating the date via JavaScript, by calling the method and passing either a JavaScript or a date string in the format of the , the DateTimePicker will re-bind to its targets and correctly format the new date value.

To reset the DateTimePicker instance by calling the method and not passing any value the picker will either clear the current date or will set it to today depending on if the is set the or .

dtp.setDate();

dtp.setDate(new-date)

Methods

Method Parameters Description Return Type
Refreshes the DateTimePicker instance by re-binding to its target and correctly formating the input elements attribute.
Updates the DateTimePicker instance current date and correctly formats the given date value, which must be supplied as either a JavaScript or as a date string in the format of the . To reset the DateTimePicker instance by calling the method and not passing any value the picker will either clear the current date or will set it to today depending on if the is set the or .
Returns the current date for each of the DateTimePicker instance’s targets in the form of either a single JavaScript date object, a single formatted date string, an array of date objects or an array of formatted date strings. For each target without a value is returned. If a format string is passed, the method will supply a string representation of the date or dates. If no parameter is passed the method will supply JavaScript date objects. If the DateTimePicker instance is configured to be the time picker only then the date portion of the date will be set as 1st January of the current year. / / /
, Returns a string representation of the given date object depending on the supplied format string. Supported format symbols are described in the Dateformatting section.
, Returns a date object representation of the given formatted date string. The format string parameter must equal the format that the date string is supplied. Supported format symbols are described in the Dateformatting section.

方法

初始化日期时间选择器。

移除日期时间选择面板。

$('#datetimepicker').datetimepicker('remove');

显示日期时间选择面板。

$('#datetimepicker').datetimepicker('show');

隐藏日期时间选择面板。

$('#datetimepicker').datetimepicker('hide');

参数:

currentDate (Date).

更新指定的时间。

$('#datetimepicker').datetimepicker('update', new Date());

如果更新时间为现在时间,则不需要传值。

$('#datetimepicker').datetimepicker('update');

设置开始时间,小于开始时间的将被禁用, 接受: 值。

$('#datetimepicker').datetimepicker('setStartDate', '2015-01-01');

如果忽略该值,将不启用该选项。

$('#datetimepicker').datetimepicker('setStartDate');
$('#datetimepicker').datetimepicker('setStartDate', null);

设置结束时间,大于结束时间的将被禁用, 接受: 值。

$('#datetimepicker').datetimepicker('setEndDate', '2014-12-31');

如果忽略该值,选项无效。

$('#datetimepicker').datetimepicker('setEndDate');
$('#datetimepicker').datetimepicker('setEndDate', null);

禁用星期的列数: 接受 或 类型参数。

// 周日和周六将被禁用
$('#datetimepicker').datetimepicker('setDaysOfWeekDisabled', ,6);

如果忽略该值,选项无效。

$('#datetimepicker').datetimepicker('setDaysOfWeekDisabled');
$('#datetimepicker').datetimepicker('setDaysOfWeekDisabled', null);

С этим читают