Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date day (05/12/2011 to 12th)

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

like image 785
JohnBoy Avatar asked May 14 '11 17:05

JohnBoy


People also ask

How do you calculate days from one date to another?

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.

What is the easiest way to calculate day from date?

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.

How do you convert a date to the number of days in Python?

We use the datetime module() to calculate the number of days between two dates using python.


3 Answers

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/

like image 120
Alnitak Avatar answered Sep 26 '22 16:09

Alnitak


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' );
like image 21
Nobody Avatar answered Sep 22 '22 16:09

Nobody


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 :-)

like image 40
mellamokb Avatar answered Sep 23 '22 16:09

mellamokb