How to Format Date with Ordinal Number Suffix (st, nd, rd, th) in JavaScript

Ordinal number format helps to add st/nd/rd/th suffix to the calendar date. It is also a user-friendly way to represent a date on the web page. Mostly the ordinal suffix is added to the day of the month in a date string. The st/nd/rd/th date format can be added in the client-side script using JavaScript.

We will create a custom JavaScript function to get ordinal suffix (st, nd, rd, th). The nth() function st/nd/rd/th format based on the given number using JavaScript.

const nth = function(d) {
    if (d > 3 && d < 21) return 'th';
    switch (d % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
}

Use the nth() function to format date with ordinal number suffix in JavaScript. The following code snippet will show you how to convert date to ordinal format using JavaScript.

const nth = function(d) {
    if (d > 3 && d < 21) return 'th';
    switch (d % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
    }
};

const dateObj = new Date();
const date = dateObj.getDate();
const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][dateObj.getMonth()];
const year = dateObj.getFullYear();

var dateString = date+nth(date)+' '+month+' '+year;

Leave a reply

keyboard_double_arrow_up