Convert Date of Day (12/05/2011 to 12)

I am trying to hide the date up to the day number followed by "st", "nd", "rd" or "th" depending on the day. I am new to javascript, so I don't know where to start.

eg.

01/05/2011 = 1st
02/05/2011 = 2nd
03/05/2011 = third
12/05/2011 = 12th
05/22/2011 = 22nd

thanks

+6
source share
5 answers

First enter 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/

+10
source
 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' ); 
+9
source

You can 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 correct suffix. In most cases this will be th , with the exception of exceptions. What are the exceptions? 1, 21, 31 = st , 2, 22 = nd , 3, 23 = rd , everything else is th . Therefore, we can use mod % to check if it ends with 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 may be bored and use the library :-)

+2
source

I wrote this simple function the other day. Although you don't need large numbers for the date, it will also serve higher values ​​(1013, 36021st, etc.)

 var fGetSuffix = function(nPos){ var sSuffix = ""; switch (nPos % 10){ case 1: sSuffix = (nPos % 100 === 11) ? "th" : "st"; break; case 2: sSuffix = (nPos % 100 === 12) ? "th" : "nd"; break; case 3: sSuffix = (nPos % 100 === 13) ? "th" : "rd"; break; default: sSuffix = "th"; break; } return sSuffix; }; 
+1
source

You can do this easily using datejs using the S format specifier .

0
source

Source: https://habr.com/ru/post/888123/


All Articles