0

Forgive asking a question that I know has been asked many times before, but I am new to Javascript, and I have looked through this and many other sites examples given, and I just cannot figure out the examples given.

I am trying to figure out how to have a date be shown on an HTML page that has the date as an ordinal. I will be generating todays and tomorrows dates.

For example, I can get "July 24" as an output no problem, but I cannot figure out how to have it show "July 24th".

Here is the code that I have sofar:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<script type="text/javascript">
var today=new Date()
var monthname=new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
document.write(monthname[today.getMonth()] + " ")
document.write(today.getDate())
</script>
<br>
<script type="text/javascript">
var tomorrow=new Date()
var monthname=new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
document.write(monthname[tomorrow.getMonth()] + " ")
document.write(tomorrow.getDate() + 1)
</script>
</body>
</html>
wb6vpm
  • 1
  • 2

1 Answers1

0

You can use a small function like the following to add an ordinal to positive integers:

function addOrdinal(n) {
  var x = n%100;
  var ords = ['th','st','nd','rd'];
  if (x == 11 || x == 12 || x == 13) return ords[0];
  return ords[n%10] || ords[0];
}
RobG
  • 142,382
  • 31
  • 172
  • 209