3 Ways To Format Date In Javascript – Simple Examples

Welcome to a tutorial on how to format a date in Javascript. Yes, formatting a date in Javascript is confusing, and everyone on the Internet seems to suggest a different method. So here it is, to solve the mystery once and for all.

The common ways to format a date in Javascript are:

  1. Use one of the many native “to date string” functions.
    • DATE.toString()
    • DATE.toDateString()
    • DATE.toTimeString()
    • DATE.toLocaleString()
    • DATE.toLocaleDateString()
    • DATE.toLocaleTimeString()
    • DATE.toUTCString()
    • DATE.toISOString()
  2. Use a date-time format object.
    • var dateobj = new Date();
    • var formatted = new Intl.DateTimeFormat("en-US", { dateStyle: 'full', timeStyle: 'long' }).format(dateobj);
  3. Manually format the date.
    • var dateobj = new Date();
    • var date = dateobj.getDate(), month = dateobj.getMonth() + 1, year = dateobj.getFullYear();
    • var formatted = `${date}/${month}/${year}`;

That should cover the basics, but read on for more examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Format Date Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

JAVASCRIPT DATE FORMAT

All right, let us now get into the various ways and examples on how to format a date in Javascript.

 

1) NATIVE DATE-TO-STRING FUNCTIONS

1-date-string.html
// (A) CREATE DATE OBJECT
var dateobj = new Date("2001-02-03 04:05:06 UTC");

// (B) TO STRING
console.log(dateobj.toString()); // Full date-time string with timezone, adjusted to local timezone
console.log(dateobj.toDateString()); // Date segment only, adjusted to local timezone
console.log(dateobj.toTimeString()); // Time segment only, adjusted to local timezone
console.log(dateobj.toLocaleString()); // Date-time, adjusted to local timezone
console.log(dateobj.toLocaleDateString()); // Date only, adjusted to local timezone
console.log(dateobj.toLocaleTimeString()); // Time only, adjusted to local timezone
console.log(dateobj.toUTCString()); // Date-Time in UTC
console.log(dateobj.toISOString()); // ISO 8601

Yes, Javascript does offer a lot of native date-to-string functions. But take note that they are either tied to the user’s locale or International standards – If you want a specific “custom date format”, these are pretty much useless.

 

 

2) DATE-TIME FORMAT OBJECT

2-date-format.html
// (A) CREATE DATE OBJECT
var dateobj = new Date();

// (B) FORMAT DATE OBJECT
// (B1) DATE FORMAT LOCALE
var formatted = new Intl.DateTimeFormat("en-US").format(dateobj);
console.log(formatted);
formatted = new Intl.DateTimeFormat("en-GB").format(dateobj);
console.log(formatted);

// (B2) FORMAT DAY, DAY OF WEEK, MONTH, YEAR, HOUR, MIN, SEC
formatted = new Intl.DateTimeFormat('en-GB', { 
  // VALUES CAN BE "LONG", "SHORT", OR "NUMERIC"
  day: 'numeric',
  weekday: 'short',
  month: 'long', 
  year: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  // 12 OR 24 HOURS TIME
  hour12: true
}).format(dateobj);
console.log(formatted);

// (B3) SPECIFYING TIMEZONE
formatted = new Intl.DateTimeFormat('en-GB', {
  timeZone: 'Asia/Tokyo',
  timeZoneName: 'short' // LONG OR SHORT
}).format(dateobj);
console.log(formatted);

// (B4) DATE TIME STYLE
formatted = new Intl.DateTimeFormat('en-GB', {
  // FULL, LONG, SHORT
  dateStyle: 'full',
  timeStyle: 'long'
}).format(dateobj);
console.log(formatted);

This is probably one of the best ways to format a date in modern Javascript, but as you can see, Intl.DateTimeFormat is not that easy to understand “out-of-the-box”.  The basic usage is new Intl.DateTimeFormat('en-GB', OPTIONS).format(DATE), and you can check out the list of localization on Wikipedia.

As for the rest of the options, I have only included some of the common ones here… There are actually so many and so confusing that I didn’t want to dump everything here. Follow up with the link in the extras section if you want more.

 

 

3) MANUAL DATE FORMAT

3-manual.html
// (A) CREATE DATE OBJECT
var dateobj = new Date("2012-11-10 08:07:06");

// (B) GET DATE "PARTS" - USER'S LOCAL TIME
var date = dateobj.getDate(), // DATE
    day = dateobj.getDay(), // DAY OF WEEK, MON-SAT IS 1-6, BUT SUN IS 0
    month = dateobj.getMonth() + 1, // MONTH, JAN-DEC IS 0-11
    year = dateobj.getFullYear(), // FULL YEAR, 4 DIGITS
    hours = dateobj.getHours(), // HOURS
    mins = dateobj.getMinutes(), // MINUTES
    secs = dateobj.getSeconds(); // SECONDS

// (C) GET DATE "PARTS" - IN UTC
var udate = dateobj.getUTCDate(),
    uday = dateobj.getUTCDay(),
    umonth = dateobj.getUTCMonth() + 1, 
    uyear = dateobj.getUTCFullYear(),
    uhours = dateobj.getUTCHours(),
    umins = dateobj.getUTCMinutes(),
    usecs = dateobj.getUTCSeconds();

// (D) PREPEND ZERO
var prezero = function (num) {
  return num<10 ? "0"+num : num ;
};

// (E) MANUAL FORMAT
// DD/MM/YYYY
var formatted = `${prezero(date)}/${prezero(month)}/${year}`;
console.log(formatted);

// MM/DD/YYYY
var formatted = `${prezero(month)}/${prezero(date)}/${year}`;
console.log(formatted);

// YYYY-MM-DD HH:MM:SS
formatted = `${year}-${prezero(month)}-${prezero(date)} ${prezero(hours)}:${prezero(mins)}:${prezero(secs)}`;
console.log(formatted);

// MANUAL MONTH NAMES...
var months = {
  1 : "Jan", 2 : "Feb", 3 : "Mar", 4 : "Apr",
  5 : "May", 6 : "Jun", 7 : "Jul", 8 : "Aug",
  9 : "Sep", 10 : "Oct", 11 : "Nov", 12 : "Dec"
};
var formatted = `${prezero(date)} ${months[month]} ${prezero(year)}`;
console.log(formatted);

Once upon a time in the Dark Ages of the Internet, we have to manually format a date in Javascript… Actually, we still do this today. It may look massive at first, but it is pretty straightforward.

  • We extract the “parts” from the date object itself – The date, day, month, year, hour, minute, second.
  • Then manually “reconstruct” into the date format that we want.

A little roundabout, but it offers the greatest flexibility in however you want to format the date.

 

 

USEFUL BITS & LINKS

That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

Javascript Date Format (click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *