Formatting dates in JavaScript: A Complete Guide

Written by Shan Shah
Updated on October 31, 2022
2 mins read
formatting dates in javascript

Formatting dates in JavaScript can be a little tricky. Many developers rely on third-party libraries to format dates.

Today, I will share a glimpse of Javascript built-in date Objects. So you can start using it easily and quickly in your next project.

There are several methods to format a date in javascript.

Date Object comes with super helpful methods which you can utilize to get the date in a proper format.

Once you call it as a function, it returns the current date and time of the browser, but when you call it as a constructor, it returns a new Date Object along with methods.

Date();

'Mon Oct 10 2022 13:04:29 GMT+0500 (Pakistan Standard Time)'

new Date();

You will also get the current date, but now you can call the object methods.

You can get the list of all available methods from mdn docs like:

  • getFullYear - (yyyy)
  • getMonth - (0-11)
  • getDate - (1-31)
  • getHours - (0-23)
  • getMinutes - (0-59)
  • getSeconds - (0-59)
  • getDay- (0-6) Where 0 represents Sunday
  • and much more

You can use these methods to get the desired time. But still, we need some workaround to get the actual human-readable date and time for professional web applications.

Timezones:

There are many time zones, but we mostly consider local and universal time (UTC) or GMT.

By default, almost every date method returns local time.

toLocaleDateString

It returns a string of date portions for a specific date according to the user's time zone.

You can pass two arguments, locales and options.

Locales are the language's short notation like "en-US" for American English, "en-GB" for British English, "hi-IN" for Hindi, "ur" for Urdu, etc.

Options is an object which accepts additional formatting information like:

  • day: (numeric | 2-digit)
  • weekday: (narrow | short | long)
  • year: (numeric | 2-digit)
  • month: (numeric | 2-digit | narrow | long | short)
  • second: (numeric | 2-digit)
  • minute: (numeric | 2 digit)
  • hour: (numeric | 2-digit)

Examples:

const event = new Date();

const options = {
  day: '2-digit',
  year: '2-digit',
  month: 'long',
  weekday: 'short'
}

event.toLocaleDateString('en-US', options);   
formatting dates in javascript toLocaleDateString example

P.S: The customization level with this approach is very low.

If you want to use more complex date formats, you'll need to create custom formats.

The following helpful resources can help you pick up custom date formats easily:

Formatting Dates in JavaScript (Helpful Resources):

Project Based Tutorials
Tips & Tricks
Modern Technologies
Real-World Challenges
Creative Content
Build-Apps from Scratch
Web Development Content
17+ Videos Published
Coder Champ © 2021 - 
Privacy Policy
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram