How to Format Dates as yyyy-mm-dd in JavaScript

Ever needed to convert dates into a more universally accepted format in JavaScript? You’re not alone. We often find ourselves in situations where we need to represent dates in a specific style, and ‘yyyy-mm-dd’ is one of the most common.

Let’s dive into the world of JavaScript date formatting together. We’ll explore how you can easily transform dates into the ‘yyyy-mm-dd’ format. This might just make your coding journey a little smoother!

In this post, we will be looking at the following 3 ways to format dates as yyyy-mm-dd in JavaScript:

  • By using the toISOString() method
  • By using the Intl.DateTimeFormat object
  • By manually constructing a formatted date string

Let’s explore each…

#1 – By using the toISOString() method

By using the toISOString() method

The toISOString() method in JavaScript returns a string in a simplified extended ISO format (YYYY-MM-DDTHH:mm:ss.sssZ), which we can modify to get the date in the format YYYY-MM-DD. Let’s examine this with the help of a code example.


let date = new Date();
let formattedDate = date.toISOString().split('T')[0];
console.log(formattedDate);

How it works

The toISOString() method converts a Date object into a string, using the ISO standard. Our aim here is to extract only the date (YYYY-MM-DD) portion, so we split the string at ‘T’ and pick the first part.

  • The new Date() creates a new Date object with the current date and time.
  • The toISOString() method is then invoked on this Date object, which converts the Date into a string in the ISO format: YYYY-MM-DDTHH:mm:ss.sssZ.
  • This string is split into an array of two strings using the split('T') method, where ‘T’ is the delimiter. The first element of the array is the date (YYYY-MM-DD) and the second element is the time (HH:mm:ss.sssZ).
  • We then select the first element of the resultant array, which is the date part we’re interested in.
  • Finally, the formatted date is output to the console using console.log(formattedDate).

#2 – By using the Intl.DateTimeFormat object

By using the Intl.DateTimeFormat object

We will utilize JavaScript’s Intl.DateTimeFormat object to format a date as ‘yyyy-mm-dd’. This object allows us to format dates according to locale, and by specifying the ‘year’, ‘month’, and ‘day’ options we can achieve the desired formatting. Here’s an example:


const formatDate = (date) => {
 return new Intl.DateTimeFormat('en-GB', {
 year: 'numeric', 
 month: '2-digit', 
 day: '2-digit'
 }).format(date);
}

console.log(formatDate(new Date()));

How it works

The code sample provided above formats a given date into the ‘yyyy-mm-dd’ format by using the ‘Intl.DateTimeFormat’ object of JavaScript, which is used to format date and time according to locale. In this case, ‘en-GB’ locale is used with specified options for year, month, and day.

  • First, we define a function named ‘formatDate’ which takes a ‘date’ as a parameter.
  • Inside the function, we use the ‘new Intl.DateTimeFormat()’ method. We pass two parameters to this method:
    • The first parameter, ‘en-GB’, is the locale used for formatting. ‘en-GB’ stands for English-United Kingdom which uses the ‘yyyy-mm-dd’ date format.
    • The second parameter is an options object where we specify the format of the year as ‘numeric’, month as ‘2-digit’, and day as ‘2-digit’. This will ensure we get a four-digit year, and two-digit month and day.
  • The ‘format()’ method is then called on the ‘Intl.DateTimeFormat’ object which formats the passed date according to the specified locale and options.
  • Finally, the function returns the formatted date.
  • We then log the result of calling this function with a new date to the console.

#3 – By manually constructing a formatted date string

By manually constructing a formatted date string

We will create a function that takes a Date object as input and returns the date in ‘yyyy-mm-dd’ format by extracting the year, month, and date, ensuring they are in the correct form and then concatenating them.

Now let’s move on to the JavaScript code:


function formatDate(date) {
 let year = date.getFullYear();
 let month = (1 + date.getMonth()).toString().padStart(2, '0');
 let day = date.getDate().toString().padStart(2, '0');

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

How it works

The function formatDate() takes a JavaScript Date object as its parameter. It then uses the built-in methods of the Date object to get the year, month, and day. The month is incremented by 1 because JavaScript counts months from 0-11. The padStart() method is used to ensure the month and day are always two digits long. Finally, it formats these parts into a string in ‘yyyy-mm-dd’ format.

Here’s a step-by-step explanation:

  1. The function getFullYear() is used to get the full year as a four digit number.
  2. The function getMonth() is used to get the month. However, it returns values from 0 (January) to 11 (December), so we add 1 to get the correct month.
  3. The toString() method is used to convert the month to a string.
  4. The padStart() method is used on the month to ensure it is always two digits. If the month is a single digit, it adds a ‘0’ at the start.
  5. Steps 2-4 are repeated for the day using the getDate() method.
  6. Finally, the parts are concatenated into a string using a template literal, and the formatted date string is returned from the function.

Related:

In conclusion, changing date formats to ‘yyyy-mm-dd’ in JavaScript is easy if you have the right code. This format makes it straightforward for you to sort and manage your data effectively.

Remember, JavaScript provides several methods to manipulate dates, and using the ‘toISOString’ method will give you the desired format. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *