17

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

 3 years ago
source link: https://www.codexworld.com/how-to/format-date-with-ordinal-number-suffix-st-nd-rd-th-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Home  »  How To Guides  »  JavaScript   »   How to Format Date with Ordinal Number Suffix (st, nd, rd, th) in JavaScript

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

Cancel

Comment*

Your Name*

Your Email*

Your Website


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK