Formatting dates in JavaScript: A Complete Guide

Formatting dates in JavaScript: A Complete Guide

How to get elements by class name in JavaScript? Reading Formatting dates in JavaScript: A Complete Guide 3 minutes Next 92+ Most Used WordPress Keyboard Shortcuts

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.

Javascript date format using 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.

You'll need to create custom formats if you want to use more complex date formats.

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

Formatting Dates in JavaScript (Helpful Resources):

Our Coding guides: 

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.