- JavaScript Date Formats
- JavaScript Date Output
- JavaScript ISO Dates
- Example (Complete date)
- ISO Dates (Year and Month)
- Example
- ISO Dates (Only Year)
- Example
- ISO Dates (Date-Time)
- Example
- Example
- Time Zones
- JavaScript Short Dates.
- Example
- WARNINGS !
- JavaScript Long Dates.
- Example
- Example
- Example
- Example
- Example
- Date Input — Parsing Dates
- Example
- Example
- Complete JavaScript Date Reference
- How to Format a Date with JavaScript – Date Formatting in JS
- How to Use the JavaScript Date Object
- Basic JavaScript Date Formatting Methods
- Custom Date Formatting in JavaScript
- How to Handle Time Zones When Working with Dates
- Common Date Formatting Patterns
- How to Handle Date Input
- Wrapping Up
JavaScript Date Formats
There are generally 3 types of JavaScript date input formats:
Type | Example |
---|---|
ISO Date | «2015-03-25» (The International Standard) |
Short Date | «03/25/2015» |
Long Date | «Mar 25 2015» or «25 Mar 2015» |
The ISO format follows a strict standard in JavaScript.
The other formats are not so well defined and might be browser specific.
JavaScript Date Output
Independent of input format, JavaScript will (by default) output dates in full text string format:
JavaScript ISO Dates
ISO 8601 is the international standard for the representation of dates and times.
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
Example (Complete date)
The computed date will be relative to your time zone.
Depending on your time zone, the result above will vary between March 24 and March 25.
ISO Dates (Year and Month)
ISO dates can be written without specifying the day (YYYY-MM):
Example
Time zones will vary the result above between February 28 and March 01.
ISO Dates (Only Year)
ISO dates can be written without month and day (YYYY):
Example
Time zones will vary the result above between December 31 2014 and January 01 2015.
ISO Dates (Date-Time)
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):
Example
Date and time is separated with a capital T.
UTC time is defined with a capital letter Z.
If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:
Example
UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time).
Omitting T or Z in a date-time string can give different results in different browsers.
Time Zones
When setting a date, without specifying the time zone, JavaScript will use the browser’s time zone.
When getting a date, without specifying the time zone, the result is converted to the browser’s time zone.
In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.
JavaScript Short Dates.
Short dates are written with an «MM/DD/YYYY» syntax like this:
Example
WARNINGS !
In some browsers, months or days with no leading zeroes may produce an error:
The behavior of «YYYY/MM/DD» is undefined.
Some browsers will try to guess the format. Some will return NaN.
The behavior of «DD-MM-YYYY» is also undefined.
Some browsers will try to guess the format. Some will return NaN.
JavaScript Long Dates.
Long dates are most often written with a «MMM DD YYYY» syntax like this:
Example
Month and day can be in any order:
Example
And, month can be written in full (January), or abbreviated (Jan):
Example
Example
Commas are ignored. Names are case insensitive:
Example
Date Input — Parsing Dates
If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.
Date.parse() returns the number of milliseconds between the date and January 1, 1970:
Example
You can then use the number of milliseconds to convert it to a date object:
Example
Complete JavaScript Date Reference
For a complete Date reference, go to our:
The reference contains descriptions and examples of all Date properties and methods.
How to Format a Date with JavaScript – Date Formatting in JS
Joel Olawanle
Dates are a fundamental part of many JavaScript applications, whether it’s displaying the current date on a webpage or handling user input for scheduling events.
But displaying dates in a clear and consistent format is crucial for a positive user experience.
In the past, I have written two articles on Date formatting. The first explained solely how to use the toLocaleDateString() method to format dates, while the second explained custom date formatting with the getFullYear() , getMonth() , and getDate() methods.
In this article, we’ll explore various techniques to format dates in JavaScript, enabling you to present dates in your desired format for your application.
How to Use the JavaScript Date Object
Before we dive into date formatting, let’s get familiar with the JavaScript Date object. It provides methods to work with dates and times effectively.
To create a new date instance, you can use the new Date() constructor.
const currentDate = new Date(); console.log(currentDate); // Wed May 31 2023 08:26:18 GMT+0100 (West Africa Standard Time)
The above code will output the current date and time in the default format. However, this format is not suitable for all use cases.
This is why we need to format dates so we can extract what we need from this date object.
In JavaScript, there is no direct syntax that provides you with your expected format because date format varies based on location, circumstance, and so on.
Basic JavaScript Date Formatting Methods
JavaScript provides a few built-in methods to format dates conveniently. Let’s take a look at some of these methods:
- toDateString(): This method converts the date portion of a Date object into a human-readable string format.
const date = new Date(); console.log(date.toDateString());
- toISOString(): This method converts a Date object into a string representation following the ISO 8601 format.
const date = new Date(); console.log(date.toISOString());
- toLocaleDateString(): This method returns a string representing the date portion of a Date object using the system’s local conventions.
const date = new Date(); console.log(date.toLocaleDateString());
Output: 5/30/2023 . This Format may vary based on the system’s locale. For more explanation on how this method works, read this article.
Custom Date Formatting in JavaScript
While the basic formatting methods can be useful in certain scenarios, you might often need more control over the date format.
JavaScript provides a couple ways to achieve custom date formatting:
- String Concatenation: One approach is to manually concatenate the different components of a date using string manipulation.
const date = new Date(); const formattedDate = `$-$-$`; console.log(formattedDate);
You can manipulate this however you like and come up with more creative ways of representing dates. You can read this article to understand custom date formatting in detail and this article on how to format dates with ordinal number suffixes (-st, -nd, -rd, -th) in JavaScript.
- Intl.DateTimeFormat: JavaScript’s Intl object offers powerful formatting capabilities through the DateTimeFormat object. It provides localization support and various options to format dates and times.
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', < dateStyle: 'short' >); const formattedDate = formatter.format(date); console.log(formattedDate);
Using Intl.DateTimeFormat , you can specify the desired locale and various options to format dates precisely as needed. There are more options you can use in the official documentation.
How to Handle Time Zones When Working with Dates
When working with dates, it’s essential to consider time zones, especially when dealing with global applications or time-sensitive information.
JavaScript provides methods to handle time zones effectively:
- Time Zone Offset: The getTimezoneOffset() method of the Date object returns the difference in minutes between the local time zone and UTC. You can use this offset to adjust dates for specific time zones.
- Displaying Time Zones: To display the time zone information alongside the date, you can use the toLocaleString() method with the appropriate options.
const date = new Date(); const formattedDate = date.toLocaleString('en-US', < timeZoneName: 'short' >); console.log(formattedDate);
Output: 5/30/2023, 12:00:00 AM PDT .
Common Date Formatting Patterns
Certain date formatting patterns are commonly used. Here are a few examples:
- Specific Date Format: To display a date in a specific format, such as DD/MM/YYYY , you can use Intl.DateTimeFormat with the appropriate options.
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', < day: '2-digit', month: '2-digit', year: 'numeric' >); const formattedDate = formatter.format(date); console.log(formattedDate);
- Time Format: To format the time portion of a date, you can use the hour , minute , and second options.
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', < hour: '2-digit', minute: '2-digit', second: '2-digit' >); const formattedTime = formatter.format(date); console.log(formattedTime);
How to Handle Date Input
Apart from formatting dates for display, it’s essential to handle user input for dates effectively. Here are a few considerations:
- Parsing User Input: Use the Date.parse() method or external libraries like Moment.js or Luxon to parse user-provided dates into valid Date objects.
- Validating User Input: Implement validation mechanisms to ensure the user’s input adheres to the expected date format. Regular expressions or external libraries can help with this.
Wrapping Up
Formatting dates in JavaScript is an essential skill when building web applications. By utilizing the built-in date formatting methods, custom formatting techniques, and external libraries, you can ensure dates are presented clearly and accurately.
Experiment with different approaches and stay mindful of time zones for a seamless user experience with date formatting in JavaScript.
For further study on how to format dates, check these resources:
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.