Adding a Timepicker to jQuery UI Datepicker

The timepicker addon adds a timepicker to jQuery UI Datepicker, thus the datepicker and slider components (jQueryUI) are required for using any of these. In addition all datepicker options are still available through the timepicker addon.

If you are interested in contributing to Timepicker Addon please check it out on GitHub. If you do make additions please keep in mind I enjoy tabs over spaces,.. But contributions are welcome in any form.

Back to Blog or Follow on Twitter

Donation

Has this Timepicker Addon been helpful to you?

Getting Started

Highly Recommended

Handling Time eBook

Check out the Handling Time eBook to learn from the basic setup to advanced i18n usage, and from client's javascript to the server's database.

Handling Time eBook

buy eBook + Example code

buy eBook

Subscribe to Blog and Twitter

Subscribe to my blog via email and follow @PracticalWeb on Twitter. I post for nearly every new version, so you know about updates.


Download

Download Timepicker Addon and the required CSS.

Download/Contribute on GitHub (Need the entire repo? Find a bug? See if its fixed here)

If you prefer a hosted CDN there are a couple available: CDNJS, jsDelivr.


Requirements

You also need to include jQuery and jQuery UI with datepicker and slider wigits. You should include them in your page in the following order:

  1. jQuery
  2. jQueryUI (with datepicker and slider wigits)
  3. Timepicker

Version

Version 1.6.3

Last updated on 2016-04-20

jQuery Timepicker Addon is currently available for use in all personal or commercial projects under the MIT license.

MIT License

Options

The timepicker does inherit all options from datepicker. However, there are many options that are shared by them both, and many timepicker only options:

Localization Options

currentText
Default: "Now", A Localization Setting - Text for the Now button.
closeText
Default: "Done", A Localization Setting - Text for the Close button.
amNames
Default: ['AM', 'A'], A Localization Setting - Array of strings to try and parse against to determine AM.
pmNames
Default: ['PM', 'P'], A Localization Setting - Array of strings to try and parse against to determine PM.
timeFormat
Default: "HH:mm", A Localization Setting - String of format tokens to be replaced with the time. See Formatting.
timeSuffix
Default: "", A Localization Setting - String to place after the formatted time.
timeOnlyTitle
Default: "Choose Time", A Localization Setting - Title of the wigit when using only timepicker.
timeText
Default: "Time", A Localization Setting - Label used within timepicker for the formatted time.
hourText
Default: "Hour", A Localization Setting - Label used to identify the hour slider.
minuteText
Default: "Minute", A Localization Setting - Label used to identify the minute slider.
secondText
Default: "Second", A Localization Setting - Label used to identify the second slider.
millisecText
Default: "Millisecond", A Localization Setting - Label used to identify the millisecond slider.
microsecText
Default: "Microsecond", A Localization Setting - Label used to identify the microsecond slider.
timezoneText
Default: "Timezone", A Localization Setting - Label used to identify the timezone slider.
isRTL
Default: false, A Localization Setting - Right to Left support.

Alt Field Options

altFieldTimeOnly
Default: true - When altField is used from datepicker altField will only receive the formatted time and the original field only receives date.
altSeparator
Default: (separator option) - String placed between formatted date and formatted time in the altField.
altTimeSuffix
Default: (timeSuffix option) - String always placed after the formatted time in the altField.
altTimeFormat
Default: (timeFormat option) - The time format to use with the altField.
altRedirectFocus
Default: true - Whether to immediately focus the main field whenever the altField receives focus. Effective at construction time only, changing it later has no effect.

Timezone Options

timezoneList
Default: [generated timezones] - An array of timezones used to populate the timezone select. Can be an array of values or an array of objects: { label: "EDT", value: -240 }. The value should be the offset number in minutes. So "-0400" which is the format "-hhmm", would equate to -240 minutes.

Time Field Options

controlType
Default: 'slider' - Whether to use 'slider' or 'select'. If 'slider' is unavailable through jQueryUI, 'select' will be used. For advanced usage you may pass an object which implements "create", "options", "value" methods to use controls other than sliders or selects. See the _controls property in the source code for more details.
{
	create: function(tp_inst, obj, unit, val, min, max, step){	
		// generate whatever controls you want here, just return obj
	},
	options: function(tp_inst, obj, unit, opts, val){
		// if val==undefined return the value, else return obj
	},
	value: function(tp_inst, obj, unit, val){
		// if val==undefined return the value, else return obj
	}
}
showHour
Default: null - Whether to show the hour control. The default of null will use detection from timeFormat.
showMinute
Default: null - Whether to show the minute control. The default of null will use detection from timeFormat.
showSecond
Default: null - Whether to show the second control. The default of null will use detection from timeFormat.
showMillisec
Default: null - Whether to show the millisecond control. The default of null will use detection from timeFormat.
showMicrosec
Default: null - Whether to show the microsecond control. The default of null will use detection from timeFormat.
showTimezone
Default: null - Whether to show the timezone select.
showTime
Default: true - Whether to show the time selected within the datetimepicker.
stepHour
Default: 1 - Hours per step the slider makes.
stepMinute
Default: 1 - Minutes per step the slider makes.
stepSecond
Default: 1 - Seconds per step the slider makes.
stepMillisec
Default: 1 - Milliseconds per step the slider makes.
stepMicrosec
Default: 1 - Microseconds per step the slider makes.
hour
Default: 0 - Initial hour set.
minute
Default: 0 - Initial minute set.
second
Default: 0 - Initial second set.
millisec
Default: 0 - Initial millisecond set.
microsec
Default: 0 - Initial microsecond set. Note: Javascript's native Date object does not natively support microseconds. Timepicker adds ability to simply Date.setMicroseconds(m) and Date.getMicroseconds(). Date comparisons will not acknowledge microseconds. Use this only for display purposes.
timezone
Default: null - Initial timezone set. This is the offset in minutes. If null the browser's local timezone will be used. If you're timezone is "-0400" you would use -240. For backwards compatibility you may pass "-0400", however the timezone is stored in minutes and more reliable.
hourMin
Default: 0 - The minimum hour allowed for all dates.
minuteMin
Default: 0 - The minimum minute allowed for all dates.
secondMin
Default: 0 - The minimum second allowed for all dates.
millisecMin
Default: 0 - The minimum millisecond allowed for all dates.
microsecMin
Default: 0 - The minimum microsecond allowed for all dates.
hourMax
Default: 23 - The maximum hour allowed for all dates.
minuteMax
Default: 59 - The maximum minute allowed for all dates.
secondMax
Default: 59 - The maximum second allowed for all dates.
millisecMax
Default: 999 - The maximum millisecond allowed for all dates.
microsecMax
Default: 999 - The maximum microsecond allowed for all dates.
hourGrid
Default: 0 - When greater than 0 a label grid will be generated under the slider. This number represents the units (in hours) between labels.
minuteGrid
Default: 0 - When greater than 0 a label grid will be generated under the slider. This number represents the units (in minutes) between labels.
secondGrid
Default: 0 - When greater than 0 a label grid will be genereated under the slider. This number represents the units (in seconds) between labels.
millisecGrid
Default: 0 - When greater than 0 a label grid will be genereated under the slider. This number represents the units (in milliseconds) between labels.
microsecGrid
Default: 0 - When greater than 0 a label grid will be genereated under the slider. This number represents the units (in microseconds) between labels.

Other Options

showButtonPanel
Default: true - Whether to show the button panel at the bottom. This is generally needed.
timeInput
Default: false - Allows direct input in time field
timeOnly
Default: false - Hide the datepicker and only provide a time interface.
timeOnlyShowDate
Default: false - Show the date and time in the input, but only allow the timepicker.
afterInject
Default: null - Function to be called when the timepicker or selection control is injected or re-rendered. Called in the context of the timepicker instance.
onSelect
Default: null - Function to be called when a date is chosen or time has changed (parameters: datetimeText, datepickerInstance).
alwaysSetTime
Default: true - Always have a time set internally, even before user has chosen one.
separator
Default: " " - When formatting the time this string is placed between the formatted date and formatted time.
pickerTimeFormat
Default: (timeFormat option) - How to format the time displayed within the timepicker.
pickerTimeSuffix
Default: (timeSuffix option) - String to place after the formatted time within the timepicker.
showTimepicker
Default: true - Whether to show the timepicker within the datepicker.
oneLine
Default: false - Try to show the time dropdowns all on one line. This should be used with controlType 'select' and as few units as possible.
addSliderAccess
Default: false - Adds the sliderAccess plugin to sliders within timepicker
sliderAccessArgs
Default: null - Object to pass to sliderAccess when used.
defaultValue
Default: null - String of the default time value placed in the input on focus when the input is empty.
minDateTime
Default: null - Date object of the minimum datetime allowed. Also available as minDate.
maxDateTime
Default: null - Date object of the maximum datetime allowed. Also Available as maxDate.
minTime
Default: null - String of the minimum time allowed. '8:00 am' will restrict to times after 8am
maxTime
Default: null - String of the maximum time allowed. '8:00 pm' will restrict to times before 8pm
parse
Default: 'strict' - How to parse the time string. Two methods are provided: 'strict' which must match the timeFormat exactly, and 'loose' which uses javascript's new Date(timeString) to guess the time. You may also pass in a function(timeFormat, timeString, options) to handle the parsing yourself, returning a simple object:
{
	hour: 19,
	minute: 10,
	second: 23,
	millisec: 45,
	microsec: 23,
	timezone: '-0400'
}

Formatting Your Time

The default format is "HH:mm". To use 12 hour time use something similar to: "hh:mm tt". When both "t" and lower case "h" are present in the timeFormat, 12 hour time will be used.

H
Hour with no leading 0 (24 hour)
HH
Hour with leading 0 (24 hour)
h
Hour with no leading 0 (12 hour)
hh
Hour with leading 0 (12 hour)
m
Minute with no leading 0
mm
Minute with leading 0
s
Second with no leading 0
ss
Second with leading 0
l
Milliseconds always with leading 0
c
Microseconds always with leading 0
t
a or p for AM/PM
T
A or P for AM/PM
tt
am or pm for AM/PM
TT
AM or PM for AM/PM
z
Timezone as defined by timezoneList
Z
Timezone in Iso 8601 format (+04:45)
'...'
Literal text (Uses single quotes)

Formats are used in the following ways:

  • timeFormat option
  • altTimeFormat option
  • pickerTimeFormat option
  • $.datepicker.formatTime(format, timeObj, options) utility method
  • $.datepicker.parseTime(format, timeStr, options) utility method

For help with formatting the date portion, visit the datepicker documentation for formatting dates.

Working with Localizations

Timepicker comes with many translations and localizations, thanks to all the contributors. They can be found in the i18n folder in the git repo.

The quick and cheap way to use localizations is to pass in options to a timepicker instance:

$('#example123').timepicker({
	timeOnlyTitle: 'Выберите время',
	timeText: 'Время',
	hourText: 'Часы',
	minuteText: 'Минуты',
	secondText: 'Секунды',
	currentText: 'Сейчас',
	closeText: 'Закрыть'
});

However, if you plan to use timepicker extensively you will need to include (build your own) localization. It is simply assigning those same variables to an object.

As you see in the example below we maintain a separate object for timepicker. This way we aren't bound to any future changes within datepicker.

$.datepicker.regional['ru'] = {
	closeText: 'Закрыть',
	prevText: '<Пред',
	nextText: 'След>',
	currentText: 'Сегодня',
	monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
	'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
	monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
	'Июл','Авг','Сен','Окт','Ноя','Дек'],
	dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
	dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
	dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
	weekHeader: 'Не',
	dateFormat: 'dd.mm.yy',
	firstDay: 1,
	isRTL: false,
	showMonthAfterYear: false,
	yearSuffix: ''
};
$.datepicker.setDefaults($.datepicker.regional['ru']);


$.timepicker.regional['ru'] = {
	timeOnlyTitle: 'Выберите время',
	timeText: 'Время',
	hourText: 'Часы',
	minuteText: 'Минуты',
	secondText: 'Секунды',
	millisecText: 'Миллисекунды',
	timezoneText: 'Часовой пояс',
	currentText: 'Сейчас',
	closeText: 'Закрыть',
	timeFormat: 'HH:mm',
	amNames: ['AM', 'A'],
	pmNames: ['PM', 'P'],
	isRTL: false
};
$.timepicker.setDefaults($.timepicker.regional['ru']);

Now all you have to do is call timepicker and the Russian localization is used. Generally you only need to include the localization file, it will setDefaults() for you.

As of version 1.4.5 a combined file of all localizations available is included. This file DOES NOT call setDefaults(), so you will need to pass, or merge with your options.

$('#example123').timepicker($.timepicker.regional['ru']);

Localization files for datepicker are typically available in your jQueryUI downloads.

Examples

Basic Initializations

Add a simple datetimepicker to jQuery UI's datepicker

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

Add only a timepicker:

$('#basic_example_2').timepicker();

Format the time:

$('#basic_example_3').datetimepicker({
	timeFormat: "hh:mm tt"
});

Timepicker comes with a collection of localization files and one combined file with all available localizations. $.timepicker.regional["your localization code here"] is a simple object with preset options:

$('#basic_example_4').timepicker(
	$.timepicker.regional['es']
);

Using Timezones

Simplest timezone usage:

$('#timezone_example_1').datetimepicker({
	timeFormat: 'hh:mm tt z'
});

Define your own timezone options:

$('#timezone_example_2').datetimepicker({
	timeFormat: 'HH:mm z',
	timezoneList: [ 
			{ value: -300, label: 'Eastern'}, 
			{ value: -360, label: 'Central' }, 
			{ value: -420, label: 'Mountain' }, 
			{ value: -480, label: 'Pacific' } 
		]
});

Slider Modifications

Add a grid to each slider:

$('#slider_example_1').timepicker({
	hourGrid: 4,
	minuteGrid: 10,
	timeFormat: 'hh:mm tt'
});

Set the interval step of sliders:

$('#slider_example_2').datetimepicker({
	timeFormat: 'HH:mm:ss',
	stepHour: 2,
	stepMinute: 10,
	stepSecond: 10
});

Add sliderAccess plugin for touch devices:

$('#slider_example_3').datetimepicker({
	addSliderAccess: true,
	sliderAccessArgs: { touchonly: false }
});

Use dropdowns instead of sliders. By default if slider is not available dropdowns will be used.

$('#slider_example_4').datetimepicker({
	controlType: 'select',
	timeFormat: 'hh:mm tt'
});

Uses one line dropdowns instead of sliders.

$('#slider_example_4andHalf').datetimepicker({
	controlType: 'select',
	oneLine: true,
	timeFormat: 'hh:mm tt'
});

Create your own control by implementing the create, options, and value methods. If you want to use your new control for all instances use the $.timepicker.setDefaults({controlType:myControl}). Here we implement jQueryUI's spinner control (jQueryUI 1.9+).

var myControl=  {
	create: function(tp_inst, obj, unit, val, min, max, step){
		$('<input class="ui-timepicker-input" value="'+val+'" style="width:50%">')
			.appendTo(obj)
			.spinner({
				min: min,
				max: max,
				step: step,
				change: function(e,ui){ // key events
						// don't call if api was used and not key press
						if(e.originalEvent !== undefined)
							tp_inst._onTimeChange();
						tp_inst._onSelectHandler();
					},
				spin: function(e,ui){ // spin events
						tp_inst.control.value(tp_inst, obj, unit, ui.value);
						tp_inst._onTimeChange();
						tp_inst._onSelectHandler();
					}
			});
		return obj;
	},
	options: function(tp_inst, obj, unit, opts, val){
		if(typeof(opts) == 'string' && val !== undefined)
			return obj.find('.ui-timepicker-input').spinner(opts, val);
		return obj.find('.ui-timepicker-input').spinner(opts);
	},
	value: function(tp_inst, obj, unit, val){
		if(val !== undefined)
			return obj.find('.ui-timepicker-input').spinner('value', val);
		return obj.find('.ui-timepicker-input').spinner('value');
	}
};

$('#slider_example_5').datetimepicker({
	controlType: myControl
});

Alternate Fields

Alt field in the simplest form:

$('#alt_example_1').datetimepicker({
	altField: "#alt_example_1_alt"
});

With datetime in both:

$('#alt_example_2').datetimepicker({
	altField: "#alt_example_2_alt",
	altFieldTimeOnly: false
});

Format the altField differently:

$('#alt_example_3').datetimepicker({
	altField: "#alt_example_3_alt",
	altFieldTimeOnly: false,
	altFormat: "yy-mm-dd",
	altTimeFormat: "h:m t",
	altSeparator: " @ "
});

With inline mode using altField:

$('#alt_example_4').datetimepicker({
	altField: "#alt_example_4_alt",
	altFieldTimeOnly: false
});

Time Input

Allows time displayed inside the picker to allow being typed in.

$('#input_example_1').datetimepicker({
	timeInput: true,
	timeFormat: "hh:mm tt"
});

Don't show any sliders, only the time input.

$('#input_example_2').datetimepicker({
	timeInput: true,
	timeFormat: "hh:mm tt",
	showHour: false,
	showMinute: false
});

Time Restraints

Set the min/max hour of every date:

$('#rest_example_1').timepicker({
	hourMin: 8,
	hourMax: 16
});

Set the min/max date numerically:

$('#rest_example_2').datetimepicker({
	numberOfMonths: 2,
	minDate: 0,
	maxDate: 30
});

Set the min/max date and time with a Date object:

$('#rest_example_3').datetimepicker({
	minDate: new Date(2010, 11, 20, 8, 30),
	maxDate: new Date(2010, 11, 31, 17, 30)
});

Time Ranges

Restrict a start and end date by using onSelect and onClose events for more control over functionality:

For more examples and advanced usage grab the Handling Time eBook.

var startDateTextBox = $('#range_example_1_start');
var endDateTextBox = $('#range_example_1_end');

startDateTextBox.datetimepicker({ 
	timeFormat: 'HH:mm z',
	onClose: function(dateText, inst) {
		if (endDateTextBox.val() != '') {
			var testStartDate = startDateTextBox.datetimepicker('getDate');
			var testEndDate = endDateTextBox.datetimepicker('getDate');
			if (testStartDate > testEndDate)
				endDateTextBox.datetimepicker('setDate', testStartDate);
		}
		else {
			endDateTextBox.val(dateText);
		}
	},
	onSelect: function (selectedDateTime){
		endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate') );
	}
});
endDateTextBox.datetimepicker({ 
	timeFormat: 'HH:mm z',
	onClose: function(dateText, inst) {
		if (startDateTextBox.val() != '') {
			var testStartDate = startDateTextBox.datetimepicker('getDate');
			var testEndDate = endDateTextBox.datetimepicker('getDate');
			if (testStartDate > testEndDate)
				startDateTextBox.datetimepicker('setDate', testEndDate);
		}
		else {
			startDateTextBox.val(dateText);
		}
	},
	onSelect: function (selectedDateTime){
		startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate') );
	}
});

Timepicker also includes some shortcut methods for ranges:

var startDateTextBox = $('#range_example_2_start');
var endDateTextBox = $('#range_example_2_end');

$.timepicker.datetimeRange(
	startDateTextBox,
	endDateTextBox,
	{
		minInterval: (1000*60*60), // 1hr
		dateFormat: 'dd M yy', 
		timeFormat: 'HH:mm',
		start: {}, // start picker options
		end: {} // end picker options					
	}
);

To use only times for a time range use $.timepicker.timeRange():

var startTimeTextBox = $('#range_example_3_start');
var endTimeTextBox = $('#range_example_3_end');

$.timepicker.timeRange(
	startTimeTextBox,
	endTimeTextBox,
	{
		minInterval: (1000*60*60), // 1hr
		timeFormat: 'HH:mm',
		start: {}, // start picker options
		end: {} // end picker options
	}
);

Even though this plugin focuses on datetime, it also provides a dateRange function:

var startDateTextBox = $('#range_example_4_start');
var endDateTextBox = $('#range_example_4_end');

$.timepicker.dateRange(
	startDateTextBox,
	endDateTextBox,
	{
		minInterval: (1000*60*60*24*4), // 4 days
		maxInterval: (1000*60*60*24*8), // 8 days
		start: {}, // start picker options
		end: {} // end picker options
	}
);

Utilities

Get and Set Datetime with the getDate and setDate methods. This example uses timezone to demonstrate the timepicker regonizes the timezones and computes the offsets when getting and setting.

var ex13 = $('#utility_example_1');

ex13.datetimepicker({
	timeFormat: 'hh:mm tt z',
	separator: ' @ ',
	showTimezone: true
});

$('#utility_example_1_setdt').click(function(){
	ex13.datetimepicker('setDate', (new Date()) );
});

$('#utility_example_1_getdt').click(function(){
	alert(ex13.datetimepicker('getDate'));
});

Use the utility function to format your own time. $.datepicker.formatTime(format, time, options)

format
required - string represenation of the time format to use
time
required - hash: { hour, minute, second, millisecond, timezone }
options
optional - hash of any options in regional translation (ampm, amNames, pmNames..)

Returns a time string in the specified format.

$('#utility_example_2').text(
	$.datepicker.formatTime('HH:mm z', { hour: 14, minute: 36, timezone: '+2000' }, {})
);

Use the utility function to parses a formatted time. $.datepicker.parseTime(format, timeString, options)

format
required - string represenation of the time format to use
time
required - time string matching the format given in parameter 1
options
optional - hash of any options in regional translation (ampm, amNames, pmNames..)

Returns an object with hours, minutes, seconds, milliseconds, timezone.

$('#utility_example_3').text(JSON.stringify( 
	$.datepicker.parseTime('HH:mm:ss:l z', "14:36:21:765 +2000", {}) 
));