Display Date in MM/DD/YYYY format using JavaScript

To display a date in mm/dd/yyyy format in JavaScript, use this script

<script type="text/javascript">
var
currentDt = new Date();
var mm = currentDt.getMonth() + 1;
var dd = currentDt.getDate();
var yyyy = currentDt.getFullYear();
var date = mm + '/' + dd + '/' + yyyy;
alert(date);
</script>

OUTPUT

image

Similarly if you want to always represent the month as double digits, just add a ‘0’ as shown below:

var mm = currentDt.getMonth() + 1;
mm = (mm < 10) ? '0' + mm : mm;

The output now is:

image

If you know of a better way without using any JavaScript frameworks, I would love to hear it! Use the comments section.

2 comments: