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.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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.

Muhammad Taqi said...

good job !