How to Format a Date to YYYY MM DD in JavaScript
Table of Contents
Working with dates in JavaScript has historically been a challenge.
You want to be able to format dates in a way that is easy to read and understand, and you want to be able to parse dates in a way that is easy to read and understand.
In this post, we'll learn how to format a date in one of the most popular formats, YYYY-MM-DD
.
Formatting Dates to YYYY-MM-DD
To format a date in this format, let's start off with our Date object:
JAVASCRIPTconst date = new Date();
Now let's make use of the toISOString()
method, which converts our date object into a string following the ISO 8601 standard.
JAVASCRIPTconst dateString = date.toISOString();
JAVASCRIPTconst date = new Date();
const string = date.toISOString();
This returns us a string in this format, if you're from the US:
BASHYYY-MM-DDTHH:MM:SS.sssZ
Now, all we need to do is split the string by the T
character, and take the first element in the array:
JAVASCRIPTconst date = new Date();
const dateString = date.toISOString();
const dateParts = dateString.split("T");
const formatted = dateParts[0];
console.log(formatted);
BASHYYYY-MM-DD
If you want to remove the dashes, you can simply use a global regex to remove them
JAVASCRIPTconst date = new Date();
const dateParts = date.toISOString().split("T");
const formatted = dateParts[0].replace(/-/g, '');
console.log(formatted);
BASHYYYYMMDD
Conclusion
In this post, we looked at the easiest way to format a Date into the YYYY-MM-DD
and YYYYMMDD
format.
The key is to take advantage of the toISOString()
method and then split the string by the T
character to get format for us.
Hopefully, this has been helpful. Thanks for reading!
- Getting Started with TypeScript
- Getting Started with Solid
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Getting Started with Vuex: Managing State in Vue