How to parse and format a date in JavaScript
Parsing and formatting dates in JavaScript can be error-prone and require careful consideration of different time zones and date formats. Even JavaScript provides several built-in methods and objects, you might need a library to ensure that your applications handle dates consistently and accurately, regardless of where the date comes from or how it is displayed.
Working with a date involves converting to and from a specific format. The format can include different components such as the day, month, and year, as well as separators like slashes or dashes. There are several common date formats used around the world, including:
- ISO 8601: YYYY-MM-DDTHH:mm:ss.sssZ (e.g. 2022-05-30T00:00:00.000Z) - Short date: mm/dd/yyyy or dd/mm/yyyy (e.g. 04/24/2023 or 24/04/2023) - Long date: MMMM dd, yyyy (e.g. April 24, 2023) - RFC 2822: EEE, dd MMM yyyy HH:mm:ss GMT (e.g. Mon, 24 Apr 2023 00:00:00 GMT) - Unix timestamp: the number of seconds or milliseconds since January 1, 1970 (e.g. 1640256000)
In this tutorial, we will focus on the “dd/mm/yyyy” format and explore various ways to parse, format, and manipulate dates in this format using JavaScript. This format is the standard way of representing dates in many countries.
Parse a date
In JavaScript, parsing a date means converting a string representation of a date into a Date object. This is often necessary when working with dates that are obtained from external sources such as APIs or user input fields.
JavaScript provides several methods for parsing dates, such as Date.parse() and new Date() constructor. It’s important to note that the date string must be in a specific format that can be recognized by the parsing method. Common formats include ISO 8601, RFC 2822, and short date formats such as “mm/dd/yyyy” or “dd/mm/yyyy”.
// Parse an ISO date string const ms = Date.parse("2022-05-30T00:00:00.000Z"); console.log(ms); // 1651296000000 // Parse a non-ISO date string (may not work in some browsers) const ms2 = Date.parse("30/05/2022"); console.log(ms2); // NaN // Create a Date object from an ISO date string const dt = new Date("2022-05-30T00:00:00.000Z"); console.log(dt); // 2022-05-30T00:00:00.000Z // Create a Date object from numbers const dt2 = new Date(2022, 4, 30); // Note: month is zero-based console.log(dt2); // 2022-05-29T17:00:00.000Z
Check out those libraries in formatting section below, they also provide robust parsing capabilities. In addition to supporting a wide range of date formats, they also offer features like fuzzy parsing, which can interpret partial or ambiguous dates based on context.
Once a date is parsed in JavaScript and converted to a Date object, it can then be formatted into a string with a specific date format.
Format a date
There are different ways to format a date as “dd/mm/yyyy” in JavaScript, depending on your preference and use case. Here are some possible solutions:
- You can use the toLocaleDateString() method with a locale parameter of ‘en-GB’ to get the date in dd/mm/yyyy format. For example:
const date = new Date(); // British English uses day-month-year order console.log(date.toLocaleDateString('en-GB')); // 24/04/2023 // US English uses month-day-year order console.log(date.toLocaleDateString("en-US")); // 04/24/2023
The toLocaleDateString() function does not provide full control over the formatting of the date string, as it relies on the formatting rules and conventions defined by the locale.
- You can use the getDate() , getMonth() and getFullYear() methods to get the day, month and year of the date, and then concatenate them with slashes. You may need to add a leading zero to the day and month digits if they are less than 10. For example:
const today = new Date(); const yyyy = today.getFullYear(); let mm = today.getMonth() + 1; // month is zero-based let dd = today.getDate(); if (dd 10) dd = '0' + dd; if (mm 10) mm = '0' + mm; const formatted = dd + '/' + mm + '/' + yyyy; console.log(formatted); // 24/04/2023
- Day.js (42.9k ⭐) — A minimalist library that offers an excellent API without much overhead. It is very similar to Moment.js but much smaller in size. It also supports plugins for additional features.
const dayjs = require("dayjs"); const dt = dayjs("2022-05-30T00:00:00.000Z"); const formatted = dt.format("dd/MM/yyyy"); console.log(formatted); // 30/05/2022
- date-fns (31.4k ⭐) — A library that offers great documentation, functional architecture, and utilities that handle almost any task you can think of. It has a modular design that allows you to import only the functions you need.
const format > = require('date-fns'); const today = new Date(); const formatted = format(today, 'dd/MM/yyyy'); console.log(formatted); // 24/04/2023
- Luxon (13.8k ⭐) — A library that leverages JavaScript’s Intl for speed and slimness while providing what Intl doesn’t: an immutable user-friendly API. It also supports time zones and localization.
const DateTime > = require("luxon"); const dt = DateTime.fromFormat("31/12/2022", "dd/MM/yyyy"); const formatted = dt.toFormat("dd/MM/yyyy"); console.log(formatted); // 31/12/2022
Date.parse()
The Date.parse() static method parses a string representation of a date, and returns the date’s timestamp.
Only the date time string format is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.
Try it
Syntax
Parameters
A string in the date time string format. See the linked reference for caveats on using different formats.
Return value
A number representing the timestamp of the given date. If dateString fails to be parsed as a valid date, NaN is returned.
Description
This function is useful for setting date values based on string values, for example in conjunction with the setTime() method.
Because parse() is a static method of Date , you always use it as Date.parse() , rather than as a method of a Date object you created.
Examples
Using Date.parse()
The following calls all return 1546300800000 . The first will imply UTC time because it’s date-only, and the others explicitly specify the UTC timezone.
.parse("2019-01-01"); Date.parse("2019-01-01T00:00:00.000Z"); Date.parse("2019-01-01T00:00:00.000+00:00");
The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system, because it has both date and time.
Non-standard date strings
Note: This section contains implementation-specific behavior that can be inconsistent across implementations.
Implementations usually default to the local time zone when the date string is non-standard. For consistency, we will assume that the code uses the UTC timezone.
.parse("Jan 1, 1970"); // 0 in all implementations Date.parse("Thu, 01 Jan 1970 00:00:00"); // 0 in all implementations Date.parse("1970,1,1"); // 0 in Chrome and Firefox, NaN in Safari Date.parse("02 01 1970"); // 2678400000 in Chrome and Firefox (Sun Feb 01 1970 00:00:00 GMT+0000); // NaN in Safari // With explicit timezone Date.parse("Thu, 01 Jan 1970 00:00:00 GMT+0300"); // -10800000 in all implementations in all timezones // Single number Date.parse("0"); // 946684800000 in Chrome (Sat Jan 01 2000 00:00:00 GMT+0000); // NaN in Firefox; // -62167219200000 in Safari (Sat Jan 01 0000 00:00:00 GMT+0000) // Two-digit number that may be a month Date.parse("28"); // NaN in all implementations // Two-digit year Date.parse("70/01/01"); // 0 in all implementations // Out-of-bounds date components Date.parse("2014-25-23"); // NaN in all implementations Date.parse("Mar 32, 2014"); // NaN in all implementations Date.parse("2014/25/23"); // NaN in all implementations Date.parse("2014-02-30"); // NaN in Safari and Firefox; // 1393718400000 in Chrome (Sun Mar 02 2014 00:00:00 GMT+0000) Date.parse("02/30/2014"); // 1393718400000 in all implementations
Specifications
Browser compatibility
BCD tables only load in the browser