Home Utilities JQuery Tips & Scripts Datejs + jQuery = AutoDate & AutoDateTime

Added: 2/3/2011

Use Datejs and jQuery to validate and create smart, auto-correcting date/time input fields.

<script src="date.js"></script>
<script src="http://code.jquery.com/jquery-3.4.0.min.js"></script>

<script>
$(function(){
	$('input.autoDate').change(function() {
		var d = $(this).val();
		if (Date.parse(d) !== null) {
			$(this).val(Date.parse(d).toString('M/d/yyyy'));
		}
	});

	$('input.autoDateTime').change(function() {
		var d = $(this).val();
		if (Date.parse(d) !== null) {
			$(this).val(Date.parse(d).toString('M/d/yyyy h:mm tt'));
		}
	});
});
</script>

<form id="dateForm" action="">
Date: <input type="text" id="Date1" name="Date1" value="" class="autoDate" size="10"><br>
Date/Time: <input type="text" id="Date2" name="Date2" value="" class="autoDateTime" size="20"> <input type="submit">
</form>
Date:
Date/Time:

Add the classes "autoDate" and "autoDateTime" to any input elements that you want to convert into smart date/time fields. Try entering the following values in the above fields. (NOTE: The value is updated after the value is changed.)

3 (will enter as current month/3/current year), Now, Today, Tomorrow, July 2008, next Friday, last April, 2004.08.07, 6/4/2005, 8:15 PM, 22:30:45, +5years, +3, -2

If you use the jQuery Validation plugin, you can add the following method to validate the combined date/time values.

<script src="validate.js"></script>
<script>
$(function(){
	jQuery.validator.addMethod("isDateTime", function(value, element) {
		return this.optional(element) || (Date.parse(value) != null);
	}, "Please enter valid date/time");
	$('#dateForm').validate({
		rules:{
			Date1: {required:true, isDateTime:true},
			Date2: {required:true, isDateTime:true}
		},
	});
});
</script>