Skip to content

JavaScript date format example | Example code

  • by

Sometimes in web-developing, you need to Convert or set the date format, the date could be given or current. Some standard data are ISO, Short, and long date.

Here are some JavaScript date formats:-

TypeExample
ISO Date“2020-07-29” (The International Standard)
Short Date“07/29/2020”
Long Date“Mar 29 2020” or “29 Mar 2020”

How do you format a date with JavaScript?

Let’s see the JavaScript date format examples:-

ISO date format to display the date

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
            let dat = new Date("2020-07-29"); 
            alert(dat)
        </script> 
    </body> 
</html> 

Output:

ISO date format javascript

Short dates are written in MM/DD/YYYY format

Short dates are written with an “MM/DD/YYYY” example like this:

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
            var d = new Date("07/29/2020");
            alert(dat)
        </script> 
    </body> 
</html>  

Long dates JavaScript formate

Long dates are most often written with a “MMM DD YYYY” Example like this:

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
            var d = new Date("July 29 2020");
            alert(d)
        </script> 
    </body> 
</html>   

Get the Current date in JS

Custom date type example.

<!DOCTYPE html>
<html>
	<body>

	<script>

	function formatDate() {
    var d = new Date(),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
	}

	alert(formatDate());

	</script>

</body>
</html>

Output:

Current date in JS FUNCTION

How to change date format in JavaScript?

Answer: You do it by fetching date, month year and combine it, see below example we created function for it:-

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
        function GetFormattedDate() {
    		var todayTime = new Date();
    		var month = todayTime.getMonth() + 1;
    		var day = todayTime.getDate();
    		var year = todayTime.getFullYear();
    	return month + "/" + day + "/" + year;
		}
            alert(GetFormattedDate())
        </script> 
    </body> 
</html>   

Do comment if you have any doubts, questions or suggestions on this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

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