JavaScript: Get English ordinal suffix for the day of the month
JavaScript Datetime: Exercise-23 with Solution
Write a JavaScript function to get the English ordinal suffix for the day of the month, 2 characters (st, nd, rd, or th).
Test Data :
dt= new Date();
console.log(english_ordinal_suffix(dt));
"23rd"
dt = new Date(2015, 10, 1);
console.log(english_ordinal_suffix(dt));
"1st"
Sample Solution:-
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript function to get English ordinal suffix for the day of the month, 2 characters (st, nd, rd or th.)</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function english_ordinal_suffix(dt)
{
return dt.getDate()+(dt.getDate() % 10 == 1 && dt.getDate() != 11 ? 'st' : (dt.getDate() % 10 == 2 && dt.getDate() != 12 ? 'nd' : (dt.getDate() % 10 == 3 && dt.getDate() != 13 ? 'rd' : 'th')));
}
dt = new Date();
console.log(english_ordinal_suffix(dt));
dt = new Date(2015, 10, 1);
console.log(english_ordinal_suffix(dt));
Sample Output:
20th 1st
Flowchart:

Live Demo:
See the Pen JavaScript - Get English ordinal suffix for the day of the month-date-ex-23 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript function to get a full textual representation of the day of the week (Sunday through Saturday).
Next: Write a JavaScript function to get ISO-8601 week number of year, weeks starting on Monday.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join