re: Formatting dates with JavaScript VIEW POST

FULL DISCUSSION
 

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.

 

That's amazing! Thanks for putting this together!

 

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" }));
 

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.

 

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.

code of conduct - report abuse