I am trying to covert the date to the day number followed by "st", "nd", "rd" or "th depending on the day. I am new to javascript so have no idea where to start.
E.g.
05/01/2011 = 1st
05/02/2011 = 2nd
05/03/2011 = 3rd
05/12/2011 = 12th
05/22/2011 = 22nd
Thanks
To calculate the number of days between two dates, you need to subtract the start date from the end date. If this crosses several years, you should calculate the number of full years. For the period left over, work out the number of months. For the leftover period, work out the number of days.
Take the last 2 digits of the year. Divide it by 4 and discard any remainder. Add the day of the month to the value obtained in step 2.
We use the datetime module() to calculate the number of days between two dates using python.
First, get the date:
var date = myval.getDate();
Then find the suffix:
function get_nth_suffix(date) {
switch (date) {
case 1:
case 21:
case 31:
return 'st';
case 2:
case 22:
return 'nd';
case 3:
case 23:
return 'rd';
default:
return 'th';
}
}
demo at http://jsfiddle.net/DZPSw/
var date = new Date('05/12/2011').getDate(),
ordinal = date + (date>10 && date<20 ? 'th' : {1:'st', 2:'nd', 3:'rd'}[date % 10] || 'th');
or
ordinal = date + ( [,'st','nd','rd'][/1?.$/.exec(date)] || 'th' );
You might start with JavaScript Date/Time Functions to get the Day number:
var theDate = myDateObj.GetDate(); // returns 1-31
Then you will need to write a rule to get the proper suffix. Most of the time it will be th
, except for the exceptions. What are the exceptions? 1, 21, 31 = st
, 2, 22 = nd
, 3, 23 = rd
, everything else is th
. So we can use mod %
to check if it ends in 1, 2, or 3:
var nth = '';
if (theDate > 3 && theDate < 21) // catch teens, which are all 'th'
nth = theDate + 'th';
else if (theDate % 10 == 1) // exceptions ending in '1'
nth = theDate + 'st';
else if (theDate % 10 == 2) // exceptions ending in '2'
nth = theDate + 'nd';
else if (theDate % 10 == 3) // exceptions ending in '3'
nth = theDate + 'rd';
else
nth = theDate + 'th'; // everything else
Here's a working demo showing the endings for 1-31: http://jsfiddle.net/6Nhn8/
Or you could be boring and use a library :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With