jQuery UI: Format Date for the Datepicker

by Galo Aragoneses

HTML

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<h2>Format Date for the Datepicker</h2>

<input id="datepicker" />

<div>
    <button class="ui-button ui-widget ui-corner-all" id="getDate">Get Date</button>
</div>

<h2>Results</h2>

<div id="results">

</div>

<div style="position: absolute;bottom: 5px;">
Read about this Fiddle at: <a href="http://jsdev.wikidot.com/howto:9" target="_blank">How To: jQuery - Format Date For Datepicker</a>
</div>

CSS

/* The following styles are for display purposes and have nothing to do with the solution. */

body > div {
  margin-top: 20px;
}

#results {
  min-height: 50px;
  border: 1px solid lightgrey;
  padding: 5px;
}

JavaScript

$(function() {
	// The count variable is used for displaying results and has nothing to do with the solution.
	var count = 1;

	// Get the datepicker element.
	var $datepicker = $("#datepicker");
  
	// Create a datepicker.
  $datepicker.datepicker({ dateFormat: "dd/mm/yy" });
  
  $("#getDate").on("click", function () {
  	// Get the date.
  	var date = $datepicker.val();
    
    // Display the date.
  	$("#results").prepend("<div>" + count++ + ". The current date is: " + date);
  });
});