How to parse and format a date in JavaScript
byby.dev
Posted on May 8, 2024
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:
- Using
toLocaleDateString()
method with a locale parameter of 'en-GB' to get the date in dd/mm/yyyy format. It 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.
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
- You can use the
getDate()
,getMonth()
andgetFullYear()
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 (45.3k ⭐) — 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 (33.3k ⭐) — 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 (14.7k ⭐) — 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
Posted on May 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 22, 2024