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.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

JavaScript Media Player said...

very cool & good js tip, thank you very much for sharing.

Unknown said...

good job !