How to format a date to dd-MMM-yyyy in JavaScript

October 14, 2022 No comments javascript date date-formatting

Introduction

In JavaScript, we may need to format a date to dd-MMM-yyyy. We'll examine how to do it in this tutorial.

How to format a date to dd-MMM-yyyy in JavaScript

To format a date to dd-MMM-yyyy in JavaScript we need to create a dedicated function called formatDate():

const monthNames = [
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
const dayOfWeekNames = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
const formatDate = (date, patternStr) => {
    if (!patternStr) {
        patternStr = 'M/d/yyyy';
    }
    let day = date.getDate(),
        month = date.getMonth(),
        year = date.getFullYear(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        miliseconds = date.getMilliseconds(),
        h = hour % 12,
        hh = twoDigitPad(h),
        HH = twoDigitPad(hour),
        mm = twoDigitPad(minute),
        ss = twoDigitPad(second),
        aaa = hour < 12 ? 'AM' : 'PM',
        EEEE = dayOfWeekNames[date.getDay()],
        EEE = EEEE.substr(0, 3),
        dd = twoDigitPad(day),
        M = month + 1,
        MM = twoDigitPad(M),
        MMMM = monthNames[month],
        MMM = MMMM.substr(0, 3),
        yyyy = year + "",
        yy = yyyy.substr(2, 2)
    ;
    // checks to see if month name will be used
    patternStr = patternStr
      .replace('hh', hh).replace('h', h)
      .replace('HH', HH).replace('H', hour)
      .replace('mm', mm).replace('m', minute)
      .replace('ss', ss).replace('s', second)
      .replace('S', miliseconds)
      .replace('dd', dd).replace('d', day)

      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
      .replace('aaa', aaa);
    if (patternStr.indexOf('MMM') > -1) {
        patternStr = patternStr
          .replace('MMMM', MMMM)
          .replace('MMM', MMM);
    }
    else {
        patternStr = patternStr
          .replace('MM', MM)
          .replace('M', M);
    }
    return patternStr;
}

const twoDigitPad = (num) => num < 10 ? "0" + num : num;

To present a date in dd-MMM-yyyy format use the following:

console.log(formatDate(new Date(), 'dd-MMM-yyyy'));

Conclusion

In this post, we presented the best way to format a date to dd-MMM-yyyy in JavaScript. You can use this function to present a Date in other formats:

console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa')); // Friday, October 14, 2022 20:00:23.296 PM
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm')); // Fri, Oct 14, 2022 20:00
console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S')); // 2022-10-14 20:00:23.296
console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa')); // 10/14/2022 8:00PM
{{ message }}

{{ 'Comments are closed.' | trans }}