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 Twitter

Car BounceTry my new app to keep you informed of your car's financing status and value.

Download

Download Timepicker Addon

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

There is a small bit of required CSS:

/* css for timepicker */
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; }
.ui-timepicker-div dl dd { margin: 0 10px 10px 65px; }
.ui-timepicker-div td { font-size: 90%; }
.ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; }

Donation

Has this Timepicker Addon been helpful to you?

Some Examples

Add a simple timepicker to jQuery UI's datepicker

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

Show time in AM/PM 12 hour format

$('#example2').datetimepicker({
	ampm: true
});

Show only the time picker without date picker

$('#example3').timepicker({});

Change the format (default is "hh:mm tt")

h
Hour with no leading 0
hh
Hour with leading 0
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
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

Also related to your timeFormat, but not required, is the separator option

separator
Place holder between date and time, default=" "
$('#example4').datetimepicker({
	timeFormat: 'h:m',
	separator: ' @ '
});

Show Seconds, Minutes, or Hours

showHour
Show the hour, default=true
showMinute
Show the minute, default=true
showSecond
Show the second, default=false
showMillisec
Show the millisecond, default=false
showTimezone
Show the timezone, default=false
$('#example5').datetimepicker({
	showSecond: true,
	showMillisec: true,
	timeFormat: 'hh:mm:ss:l'
});

Hours, Minutes, Seconds in steps

stepHour
hour steps, default=0.05 (for smooth, 1 would jump to each hour)
stepMinute
minute steps, default=0.05
stepSecond
second steps, default=0.05
stepMillisec
second steps, default=0.5
$('#example6').datetimepicker({
	showSecond: true,
	timeFormat: 'hh:mm:ss',
	stepHour: 2,
	stepMinute: 10,
	stepSecond: 10
});

Default Hours, Minutes, Seconds

hour
default=0
minute
default=0
second
default=0
millisec
default=0
$('#example7').datetimepicker({
	hour: 13,
	minute: 15
});

Set the time range. For instance if you only want to allow the user to choose times between 8AM and 5PM.

hourMin
default=0
hourMax
default=23
minuteMin
default=0
minuteMax
default=59
secondMin
default=0
secondMax
default=59
millisecMin
default=0
millisecMax
default=999



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

There is also localization support. Read up on localization for datepicker for adding support for more languages. There are a few new definitions you will need to add to your language file:

timeOnlyTitle
default="Choose Time"
timeText
default="Time"
hourText
default="Hour"
minuteText
default="Minute"
secondText
default="Second"
millisecText
default="Milliecond"
currentText
default="Now"
closeText
default="Done"
ampm
default=false (true/false, Some regions do use this, some don't)

Or optionally you may add them as options as shown below with Russian.

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

The first approach (as documented in the datepicker documentation and mentioned above) is to create your own regional objects per region, then use the setDefaults method to tie these together. Setting datepicker and timepicker regionals separtely will help ensure proper wording when only using datepicker or timepicker. Here is an example:

$.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: 'миллисекунды',
	currentText: 'Теперь',
	closeText: 'Закрыть',
	ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['ru']);

To show numbered grids under the sliders you may use the following options:

hourGrid
default=0
minuteGrid
default=0
secondGrid
default=0
millisecGrid
default=0

When using ampm option hours will be displayed with an "a" or "p": 04a, 12p, etc...

$('#example10').timepicker({
	hourGrid: 4,
	minuteGrid: 10
});

When showing more than one month:

$('#example11').datetimepicker({
	numberOfMonths: 3
});

With minDate and maxDate datepicker options:

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

Get and Set Datetime:

var ex13 = $('#example13');

ex13.datetimepicker();

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

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

Use the datepicker minDate/maxDate options: (note: these must use Date objects)

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

The following demonstrates how to use timezones and timezone options.

timezoneList
An array of timezones, either with strings ['-0500','-0600',..] or objects [ { value: '-0500', label: 'EST'}, { value: '-0600', label: 'CST' },..]
defaultTimezone
The default selected timezone in the dropdown. default='+0000'
useLocalTimezone
Use the local timezone of the client's browser. default=false
timezoneIso8601
Formats the timezones in the timezone list in 8601 format

The third example here demonstrates using the abbreviation for timezones. If this is used defaultTimezone must match the value (abbreviation). Do note that useLocalTimezone may not function properly when using abbreviations as it will only work with '+0000' formats.

Daylight savings time may be interpreted as a timezone. Create your own timezoneList and specify entries for Daylight Savings or use useLocalTimezone to help get the correct offset.

$('#example15a').datetimepicker({
	timeFormat: 'hh:mm z',
	showTimezone: true
});

$('#example15b').datetimepicker({
	timeFormat: 'hh:mm z',
	showTimezone: true,
	timezoneList: [ 
			{ value: '-0500', label: 'Eastern'}, 
			{ value: '-0600', label: 'Central' }, 
			{ value: '-0700', label: 'Mountain' }, 
			{ value: '-0800', label: 'Pacific' } 
		]
});

$('#example15c').datetimepicker({
	timeFormat: 'hh:mm z',
	showTimezone: true,
	timezone: 'MT',
	timezoneList: [ 
			{ value: 'ET', label: 'Eastern'}, 
			{ value: 'CT', label: 'Central' }, 
			{ value: 'MT', label: 'Mountain' }, 
			{ value: 'PT', label: 'Pacific' } 
		]
});

Connect to the onSelect event (Use your browser's js console for this example).

$('#example16').datetimepicker({
	showSecond: true,
	showMillisec: true,
	timeFormat: 'hh:mm:ss:l',
	onSelect: function(dateText, inst){
		if(window.console)
			console.log(dateText);
	}
});

Create a datetime range with a start and end date.

var startDateTextBox = $('#example17_start');
var endDateTextBox = $('#example17_end');

startDateTextBox.datetimepicker({ 
	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({ 
	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') );
	}
});

Use the sliderAccess addon to allow timepicker sliders to work on touch devices.

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

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..)
$('#example19').text(
	$.datepicker.formatTime('hh:mm z', { hour: 14, minute: 36, timezone: '+2000' }, { ampm: false })
);

Version

Version 1.0.2

Last updated on 07/01/2012

jQuery Timepicker Addon is currently available for use in all personal or commercial projects under both MIT and GPL licenses. This means that you can choose the license that best suits your project, and use it accordingly.

GPL License

MIT License