Converting JavaScript string to date Example | Example code

Converting a string to date in JavaScript can do by using a Creating date object. It’s the easiest way to do it. The default date format in JavaScript is dd/mm/yyyy.

Example of convert string to date in JavaScript

Simple way creating date object using date string example:-

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
        var d = '2020-07-30';

        alert(new Date(d))
        </script> 
    </body> 
</html>

Output:

Converting JavaScript string to date Example

JavaScript date parse format dd/mm/yyyy

If you have the MM/DD/YYYY format which is the default for JavaScript, you can simply pass your string to Date(string) constructor. It will parse it for you.

var dateString = "07/30/202020"; // July 30

var dateObject = new Date(dateString);

Change JavaScript Date from ISO string

We have a date string in ISO format, like 2020-11-03T19:38:34.203Z and want to convert it into a date object with new Date() method.

Try the code:-

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
        var s = '2020-11-03T19:38:34.203Z';

       	date = new Date(s);
		year = date.getFullYear();
		month = date.getMonth()+1;
		dt = date.getDate();

		if (dt < 10) {
  			dt = '0' + dt;
		}
		if (month < 10) {
  		month = '0' + month;
		}

		console.log(year+'-' + month + '-'+dt);

        </script> 
    </body> 
</html> 

Output:

Change JavaScript Date from ISO string

Q: How to JavaScript date output format:

Need to output the current UTC datetime as a string with the following format:YYYY/mm/dd hh:m:sec

Answer: You can build it manually:

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
        var m = new Date();
		var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() 

        alert(dateString);
        </script> 
    </body> 
</html>   

Do comment if you have any doubts and questions on this tutorial.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.