How to Create and Format Dates in JavaScript

Alec Scully
3 min readJun 6, 2021

Date formatting has always been an issue for me to a certain extent. This has let to multiple instances of googling specific problems and surfing StackOverflow to see if any other programmers has had the same exact issues as me. I figured I would sit down and finally do what I should have done all the way at the start — read some documentation.

As it turns out, all the confusing methods and application of date formatting that I had seen all over the place wasn’t as daunting or confusing as I had once thought. To create a new date object, it is as simple as typing:

let date = new Date( )

This will create an object and assign it to a value that is the exact date and time of its creation. If I were to do this at the time of my writing this it would equal:

2021–06–06T18:19:06.829Z

You can create these objects with the current time or date, or for a specific date. Below I will list multiple ways to create a date object. For these examples, they will be made with the current day. Any object with a time setting will be set to midnight.

Here you can see a few examples in the ISO (international standard), short (06/06/2021) and long (June 06 2021) formats.

Now that you have the date objects created, you can format these dates to whatever you may need. From getting a specific day, to getting the time in seconds, etc. To find a list of methods you can use on date objects you can go here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

My Motivation to Find These Answers

Recently I was given a code challenge to access an api and create a 7-day forecast for a specific location. (GitHub, Demo) The only issue being that the date on the API was returned as:

20210606 (YYYYMMDD)

The unfortunate thing is that that date format cannot be created into a date object on its own. My new goal was to change that into a format that is accepted as a date object (2021–06–06). After that, I needed to be able to display those dates in a format of “Sunday, June 06”. You can see my workaround below:

To break it down, this function was given a date from the API, split into an array to add the dashes in the appropriate spots, and then joined together to be made into a date object. From there, I formatted the date piece by piece. I formatted the month into a locale string (Eastern Time Zone), and added an option to have it return the “long” version of the month. The day was formatted using UTCDate which returns the number of the day of the month. Lastly for the written day, I created an array that lists every day of the week and passed the number of the day of the week using .getDay( ). The return of this example is:

Sunday, June 6

I hope this blog post was informative for you. Doing a little bit of searching to solve the issue that I encountered for the code challenge was more than worth it for me.

--

--