Formatting Date With jQuery Date Picker

by Vincy. Last modified on July 6th, 2023.

Using the jQuery date picker, we can format a selected date using the dateFormat option. In a previous post, we have seen how to use jQuery datepicker in a form to select a value for a date field. It popup a calendar widget to select a date.

In this tutorial, we will see how to format a date by picking it from the calendar popup. We have a list of date formats in a select box. On changing this select value, We set the dateFormat option with a selected format.

View Demo

HTML Date Picker with Formats

This code shows the HTML for displaying an inline date picker field and a list of date formats.

formatting-date-with-jquery-date-picker

<div id="frm-date-format">
	<div class="frm-input-row">
		<div class="frm-label">Select Date:</div>
		<div><input type="text" id="datepicker" size="30" class="form-input"></div> 
	</div>
	<div class="frm-input-row">
		<div>Formats:</div>
		<div>
			<select id="date-format" onchange="setDateFormat(this.value);" class="form-input">
				<option value="mm/dd/yy">mm/dd/yy</option>
				<option value="dd/mm/yy">dd/mm/yy</option>
				<option value="yy-mm-dd">yy-mm-dd</option>
				<option value="M d, y">M d, y</option>
			</select>
		</div>
	</div>
</div>

Setting dateFormat using jQuery

This jQuery code is used to set the date format on selecting a date using the date picker. We have a function to format date, which will be called on changing date format select field.

<script>
	$(document).ready(function() {
		$( "#datepicker" ).datepicker();
	});
	function setDateFormat(date_format) {
		$( "#datepicker" ).datepicker( "option", "dateFormat", date_format );
	}
</script>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page