In the previous JavaScript tutorial, we learned about the Date() object in JavaScript and how to create them using the
new Date()
constructor. There we also learned that we can use the string date type and convert it into a Date object.
Now, in this tutorial, we will learn what are the different date formats we can use as a string, to convert it into a Date() object.
Date format
In javascript, we can represent string data in 3 different formats.
Type | Format | Example |
ISO | "YYYY-MM-DD" | "2022-12-30" |
Short | "MM/DD/YYYY" | "12/30/2022" |
Long | "Month DD YYYY " or "DD Month YYYY" | "Dec 30 2022" or "30 Dec 2022" |
JS ISO Date
In ISO ( International Organization for Standardization) format, we represent the Date in (YYYY-MM-DD) format.
Example
By default the Date is converted into user browser-specific timezone, in my case, it converted into India Standard Time.
ISO Date with Year and Month
We can also specify only Year and Month data and create a Date object with (YYYY-MM) format only, and the rest of the details like time day, etc will be filled automatically.
Example
As you can see that the time
(05:30:00)
and day
01
automatically assigned to the date object when we only specify the year and month.
ISO Date with Year
We can also only pass the Year data and the Date() object will set the rest of the data automatically.
Example
JS ISO Date with date & time
We can also specify the compete date and time to create a Date object. To create a complete manual date-time object we can use the following format (YYYY-MM_DDTHH:MM:SSZ).
Example
Here the T represents the separator between date and time. And Z represents the UTC timezone(omit Z it will follow your browser timezone).
JS Short Dates
In the short Date, we represent the dat2 in the following format "MM/DD/YYYY"
Example
Some browser throw an error if we do not specify the leading 0 before the data ex"23-3-2022"
so its alwayse a good practice to use leading zero to represent single digit date "23-03-2022
".
JS Long Dates
JS
Date()
object also supports the Long date format. To write the date in long date format we can use the following format "MMM DD YYYY".
Example
Parse Date into Milliseconds
We can convert a valid date into milliseconds. The Date object comes with an inbuilt parse() method which converts a valid string date into milliseconds from date
1 January 1970
.
Example
Then we can use the milliseconds to convert back into Date.
Summary
- In JavaScript, we can represent string date in 3 formats ISO, short and Long.
- In ISO we represent date using the "YYYY-MM-DD" format.
- In Short Date, we represent the date using "MM/DD/YYYY" format.
- In Long date, we represent date using "MMMM DD YYYY" format.
People are also reading: