Formatting dates with JavaScript

Jesse Skinner on April 19, 2019

There are a number of popular JavaScript date formatting libraries out there, such as Moment.js, Luxon and date-fns. Those libraries are very power... [Read Full]
markdown guide
 

I know a lot of people look for a generic .format() method on dates, and you could knock something up fairly quickly like this (incomplete):

function formatDate(format, d) {
  d = d || new Date();

  const days = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
  ];

  const dateFormats = {
    'Y': d => d.getYear() + 1900,
    'm': d => ('0' + (d.getMonth() + 1)).slice(-2),
    'j': d => d.getDate(),
    'd': d => ('0' + d.getDate()).slice(-2),
    'H': d => d.getHours(),
    'i': d => ('0' + d.getMinutes()).slice(-2),
    's': d => d.getSeconds(),
    'A': d => d.getHours() < 12 ? 'AM' : 'PM',
    'a': d => d.getHours() < 12 ? 'am' : 'pm',
    'l': d => days[d.getDay()],
    'D': d => days[d.getDay()].slice(0, 3),
    'S': d => {
      switch (d.getDate() % 10) {
        case 1: return 'st';
        case 2: return 'nd';
        case 1: return 'rd';
        default: return 'th';
      }
    }
  };

  let output = '';
  let escapeNext = false;

  for (index in format) {
    const letter = format[index];

    if (escapeNext) {
      output += letter;
      escapeNext = false;
      continue;
    }

    if (letter == '\\') {
      escapeNext = true;
      continue;
    }

    if (dateFormats.hasOwnProperty(letter)) {
      output += dateFormats[letter](d);
    }
    else {
      output += letter;
    }
  }


  return output;
}


console.log(formatDate('Y-m-d H:i'));
// 2019-04-21 12:45
console.log(formatDate('l (jS) \\a\\t H:i A'));
// Sunday (21st) at 12:45

That's not i18n or anything, and I just borrowed some of the date format from other languages (cough the PHP manual cough) but it's probably pretty similar to what a lot of these libraries sweep under the rug.

 

I code some tests for this article: repl.it/repls/WhirlwindRigidMemory...
I found toLocaleString() method has some effect. e.g. the test not passed if I don't code like this:

let date = new Date(new Date(1555861886106)
.toLocaleString("en-US", { timeZone: "Asia/Shanghai" }));
 

Had a second look, seems it's the timeZone that you added that's making the tests pass. I plan on covering timezones in a future article - maybe in the next article about manipulating dates, or maybe I'll save it for its own article since time zones in the browser can be such a headache.

 

That's interesting. Yeah I found the locale stuff to be rather unpredictable. Sometimes that's okay but I usually prefer to have more control over it.

 

That's amazing! Thanks for putting this together!

 

Many times I started projects without dates libraries dependencies. Formatting a date as described in your article is fine without a library. But when it comes to manipulating with dates like adding, subtracting, calculating duration - libraries are a real timesaver.
Thanks for your article, we really should keep in mind that date formatting can be done without serving users bunch of unnecessary JS. But I think that if you know from the start that your project will heavily use date calculations, then npm install a date library without a doubt.

 

It's funny you should say that, because my next article was going to be about manipulating dates without a library 😉

 

Oh, I'll definitely take a look at your next article to check how you manipulate with dates with vanilla javascript.

 

Hi Jesse, I truly believe your intentions are good and it's a great article as an insight about how formatting dates might work in practices but I have to disagree with some of the wording.

I'm definitely in favor of using simpler solution instead of bringing in a full library to solve a seemingly simple problem but I'm going to play the devil's advocate here and say this: dates are not a simple problem. Which is why we end up with these many libraries (too many TBH :D).

If you're not picky about how dates and times will be displayed, this can work well in many cases, but it depends on each user's operating system, and which locales are installed on their devices

Sure, unless you use the same locale for each user, which is basically what you're doing here:

function getMonthName(date) {
    const months = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
    ];

    return months[date.getMonth()];
}

I'm not an English native speaker and I live in a country of non native English speakers, so I have to take into account that if I'm working a UI for the local market displaying September won't cut it.

I might harcode my version of the list of months, but as you surely know, building untranslatable apps can give you headaches down the line if you ever have to cater more than one market. But even if you don't, I'm 100% sure you'll find people in each country that have a locale set different from the one tied to the language spoken by the majority (and there are countries, including Canada that have more than one official locale).

So whatever the app is built in, I have to think about the possibility that I might need to display the name of the month in more than one language.

With your example I could hard code all the possible lists or choose a set of "supported languages" but the Intl API gives me that for free (without a library!), why not use it?

> new Intl.DateTimeFormat('default', {"month": "long"}).format(new Date())
"April"
> new Intl.DateTimeFormat('fr-CA', {"month": "long"}).format(new Date())
"avril"

If you really want to make sure that everyone is seeing a month name in English you can switch default (as you see I keep my browser in English even if it's not my first language) to en-US, en-CA or equivalents.

We could even make a case that respecting the user's wishes (how they want the dates/times to be formatted) also improves the user's experience.

I hope I've provided you with all the tools and techniques you might need to format dates and times.

You're seemingly encouraging people (correct if I'm wrong about this) to give away with internationalization features that are builtin in browsers that took so much time to be finally standardized so that they can use a set of custom made functions? This is the part I disagree with the most. You brushed them aside quickly and I fear that someone down the line will read the paragraph "What about the Internationalization API?" and dismiss the whole API because your functions are simple to understand and well documented thanks to this article.

I truly think you have good intentions and I enjoyed your explanation of the shortcomings of the builtin JS functions (one day I'll write something about the stupid shortcomings of Python's functions eheh) but I think your article should make clear that Internationalization it's an important issue, even if you don't actually plan to use it in the beginning, and that these are good examples of how date formatting might work, not "all the tools you might need".

 

You're right, the Internationalization API would probably be the preferred approach in most cases. This article is showing how to do it manually if that's what you choose or prefer to do.

 

Great article. I appreciate the approach to formatting dates using vanilla Javascript and not reaching for a library right away. Dates in Javascript can be hard enough to deal with that reaching for a library is easy to do. This is a good reminder, not only for Dates but really anything we are coding, to look into seeing if we can build something on our own without the need for a library. Using a library should add real value to your project to ensure you are getting real benefits from it. I'm looking forward to your article on manipulating dates without a library. :)

 

Awesome, thanks for the feedback! I'm looking forward to writing the next article too :)

 

Thorough coverage!

Reminds me of something I started building for a client for a similar purpose, but as we had limited needs, I never fleshed it out as much.

Am curious why you used the if/else for adding the leading 0s, and not:

d.getDate().toString().padStart(2, '0')

Only IE doesn't support padStart...

 

No particular reason. padStart works well for this.

 

This is great, thanks for sharing! It's easy to reach for a date library without thinking about how much bulk it adds, or if it's even necessary.

 

Glad you enjoyed it! I totally agree, I think it's too easy to reach for a library when solving a problem, but we need to weigh the impact on the page and the user.

code of conduct - report abuse