Home > Software > How to Format Date as YYYY-MM-DD in JavaScript

How to Format Date as YYYY-MM-DD in JavaScript

Anastasios Antoniadis

Share on X (Twitter) Share on Facebook Share on Pinterest Share on LinkedInIn JavaScript, dates are a crucial part of web applications, whether you’re displaying post publication dates in a blog, timestamps in a chat application, or handling date inputs in forms. One common requirement is formatting dates in the YYYY-MM-DD format, also known as …

Javascript

In JavaScript, dates are a crucial part of web applications, whether you’re displaying post publication dates in a blog, timestamps in a chat application, or handling date inputs in forms. One common requirement is formatting dates in the YYYY-MM-DD format, also known as the ISO 8601 date format. This format is widely used due to its unambiguous, internationally understandable format, and sorting compatibility. Despite JavaScript’s Date object providing various methods to work with dates, it doesn’t directly offer a simple way to format dates in a custom format. This article explores several methods to format a date as YYYY-MM-DD in JavaScript, covering both native JavaScript solutions and the use of libraries for more complex scenarios.

Using toISOString() and substring()

The Date object’s toISOString() method returns a string in simplified extended ISO format (YYYY-MM-DDTHH:mm:ss.sssZ), which is perfect when you need the full ISO date. However, for just the date part in YYYY-MM-DD format, you can extract the necessary portion using substring().

const date = new Date();
const formattedDate = date.toISOString().substring(0, 10);

console.log(formattedDate); // Outputs: "YYYY-MM-DD"

This method is straightforward and doesn’t require any external libraries. It works well in all modern browsers and Node.js environments.

Using Individual get Methods

Another approach involves using the getUTCFullYear(), getUTCMonth(), and getUTCDate() methods of the Date object to construct the string manually. This method provides more control over the format and allows you to avoid time zone offsets affecting the date.

function formatDate(date) {
  const year = date.getUTCFullYear();
  const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // getUTCMonth() returns 0-11
  const day = String(date.getUTCDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

const date = new Date();
console.log(formatDate(date)); // Outputs: "YYYY-MM-DD"

Using padStart(2, '0') ensures that the month and day are always two digits, which is necessary for single-digit months and days.

Using toLocaleDateString()

The toLocaleDateString() method returns the date portion of a Date object as a string, using locale conventions. With the locales and options arguments, you can specify the output format.

function formatDate(date) {
  return date.toLocaleDateString('en-CA', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  });
}

const date = new Date();
console.log(formatDate(date)); // Outputs: "YYYY-MM-DD"

The 'en-CA' locale (Canadian English) is used here because it naturally formats dates as YYYY-MM-DD. While this method is elegant, be cautious as the output might vary by runtime environment or browser due to differences in how locales are implemented.

Using Date-fns or Moment.js

For applications requiring extensive date manipulation, formatting libraries like Date-fns or Moment.js can simplify the task.

With Date-fns

import { format } from 'date-fns';

const date = new Date();
console.log(format(date, 'yyyy-MM-dd')); // Outputs: "YYYY-MM-DD"

With Moment.js

import moment from 'moment';

const date = new Date();
console.log(moment(date).format('YYYY-MM-DD')); // Outputs: "YYYY-MM-DD"

Both libraries offer a wide range of functionalities for handling dates, including formatting. Choosing between them might depend on your project’s size and needs—Moment.js is more feature-rich but larger, while Date-fns offers a modular approach.

Conclusion

Formatting dates as YYYY-MM-DD in JavaScript can be achieved through various methods, each with its advantages. Native JavaScript solutions provide straightforward ways to format dates without additional dependencies, making them suitable for simpler applications. However, for more complex scenarios involving extensive date manipulation, using a library like Date-fns or Moment.js might be more convenient, offering powerful and flexible date handling capabilities. Whichever method you choose, correctly formatting dates is essential for creating internationally understandable and unambiguous date representations in your web applications.

Anastasios Antoniadis
Follow me
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x