Formatting Date in JavaScript

Changfeng Tan
1 min readApr 8, 2021

--

Have you ever facing formatting a date datatype into a proper string object and display it on your web applications? I have faced this several times when working on my projects and especially when receiving raw data of DateTime format of string from an API.

2020–04–01T11:00:00.000+00:00 in the database is not something you want to display to your web user.

I ended up searching on StackOverflow and MDN every time when I start programming in JavaScript. So it leads me to create this post to save time and hope it will help anyone who may find this useful.

//Pretend this is the datetime string from your api response.
const rawDate = "2020–04–01T11:00:00.000+00:00";
const myDate = new Date(rawDate);// This will create a date object //from your rawDate variable.const year = myDate.getFullYear().toString();
const month = (myDate.getMonth() + 1).toString(); // month start //from 0
const date = myDate.getDate().toString();

Now you may want to start creating a new formated string like:

const displayDate = `${date/month/year}`;

The new string object will be 1/4/2020 from the context. We can make it even better by checking the length and it is your choice whether to add a leading ‘0’ or not. E.g

if (date.length === 1) date = '0' + date

We can also format the date as 01 April 2020, in order to get the April we can use:

let options = { month: 'long'};
console.log(new Intl.DateTimeFormat('en-US', options).format(myDate));
// April

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response