JavaScript Date Formats

Date objects represent a single moment in time in a platform-independent format. There are commonly 3 types of input JavaScript date formats:

JavaScript Date Formats

JavaScript Date Formats – Time Zones

JavaScript will use the browser’s time zone when we set a date, without specifying the time zone.

Short Dates

The “MM/DD/YYYY” syntax is used for short dates:

WARNINGS!
The months or days with no leading zeroes may produce an error in some browsers:

Because the behavior of “YYYY/MM/DD” is undefined so some browsers may guess the format and some will return NaN.

Long Dates

Using the “MMM DD YYYY” syntax the long dates are most often written:

Date Output

JavaScript output dates in full-text string format by default:

ISO Dates

For the representation of dates and times ISO 8601 is the international standard The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:

ISO Dates (Date-Time)

ISO dates are written with hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):

With a capital T, Date and time are separated.

With a capital Z, UTC (Universal Time Coordinated) time is defined. If we want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:

Date Input – Parsing Dates

We can use the Date.parse() method to convert the date into milliseconds. It returns the number of milliseconds between the date and January 1, 1970:

<!DOCTYPE html>
<html>
<body>

<script>
let sec = Date.parse("September 19, 2021");
document.write(sec);
</script>
</body>
</html> 

Output:

image 90

We can also convert the number of milliseconds to a date object:

<!DOCTYPE html>
<html>
<body>

<script>
let sec = Date.parse("September 19, 2021");
const t = new Date(sec);
document.write(t);
</script>

</body>
</html> 

Output:

image 89