JavaScript date format
The JavaScript date object can be used to get a year, month and day. We can display a timer on the webpage with the help of a JavaScript date object.
There are many types of date formats in JavaScript: ISO Date, Short Date, and Long Date. The formats of JavaScript’s date are defined as follows:
ISO date
Short date
Long date
The ISO date format follows a strict JavaScript’s standard, while the other formats (Short date and Long date) are browser dependent and not so well defined.
Now, let’s understand these date formats individually.
ISO date
The ISO 8601 is the international standard for the times and dates, and the syntax (YYYY-MM-DD) of this standard is the preferred date format in JavaScript.
The example of using the ISO date is given below.
Example
The output of the below code will display the complete date, which is relative to the current time zone.
Output
Now, we are discussing some other formats of the ISO date. Here, we are writing the input date and displaying the result that occurred when we use the corresponding syntax.
We can write the ISO dates using the following syntaxes.
1. This is a complete date format using ISO date.
let val = new Date(“2020-08-01”);
2. In this format, we specify only year and month (YYYY-MM) without day.
let val = new Date(“2020-08”);
3. In the third syntax, we only specify the year (YYYY) without month and day.
let val = new Date(“2020”);
4. Now, in the fourth syntax, we specify the date with added hours, minutes, and seconds. (YYYY-MM-DDTHH:MM:SSZ). In this format, the date and time are separated with the letter ‘T’ and the letter ‘Z’. We get different results in different browsers if we remove these characters.
JavaScript uses the browser’s time zone if we set the date without specifying the time zone.
let val = new Date(“2020-08-01T07:05:00Z”);
Now, we discuss the short date format along with an example.
JavaScript Short Date
The “MM/DD/YYYY” is the format used to write short dates. Now, we understand the short date by using an example.
Example
Here, we are specifying the short date format, i.e., “MM/DD/YYYY”.
Output
After the execution of the above code, the output will be –
JavaScript Long Date
The “MMM DD YYYY” is the format used to write Long dates. The month and date can be written in any order, and it is allowed to write a month in abbreviated (Aug) form or in full (August).
Now, we understand the Long date by using an example.
Example
Here, we are using the Long date format, i.e., “MMM DD YYYY”, and specifying the month in abbreviated form.
Output