javascript date ordinal-indicator

JavaScript nuevo Fecha Ordinal(st, nd, rd, th)



date ordinal-indicator (12)

Aquí hay un liner inspirado en las otras respuestas. Se prueba y tomará 0 y números negativos.

function getOrdinalNum(n) { return n + (n > 0 ? [''th'', ''st'', ''nd'', ''rd''][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : ''''); }

Si es posible, sin las bibliotecas de JavaScript o muchos códigos torpes, estoy buscando la forma más sencilla de formatear una fecha dentro de dos semanas en el siguiente formato:

13th March 2013

El código que estoy usando es:

var newdate = new Date(+new Date + 12096e5); document.body.innerHTML = newdate;

que devuelve la fecha y la hora dentro de dos semanas, pero así: Mié 27 de marzo 2013 21:50:29 GMT + 0000 (Hora estándar de GMT)

Aquí está el código en jsFiddle .

¡Cualquier ayuda sería apreciada!


Aquí hay una solución fácil:

var date = today.getDate() + (today.getDate() % 10 == 1 && today.getDate() != 11 ? + ''st'': (today.getDate() % 10 == 2 && today.getDate() != 12 ? + ''nd'': (today.getDate() % 10 == 3 && today.getDate() != 13 ? + ''rd'':''th'')));


Aquí:

Demo en vivo

var fortnightAway = new Date(+new Date + 12096e5), date = fortnightAway.getDate(), month = "January,February,March,April,May,June,July,August,September,October,November,December" .split(",")[fortnightAway.getMonth()]; function nth(d) { if(d>3 && d<21) return ''th''; // thanks kennebec switch (d % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; default: return "th"; } } document.body.innerHTML = date+nth(date) +" " +month+" "+fortnightAway.getFullYear();


Como muchos han mencionado, aquí hay otra respuesta.

Esto se basa directamente en la respuesta de @kennebec , que encontré la forma más sencilla de obtener esta fecha Ordinal generada para una fecha dada de JavaScript :

He creado dos prototype function siguiente manera:

Date.prototype.getDateWithDateOrdinal = function() { var d = this.getDate(); // from here on I''ve used Kennebec''s answer, but improved it. if(d>3 && d<21) return d+''th''; switch (d % 10) { case 1: return d+"st"; case 2: return d+"nd"; case 3: return d+"rd"; default: return d+"th"; } }; Date.prototype.getMonthName = function(shorten) { var monthsNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var monthIndex = this.getMonth(); var tempIndex = -1; if (monthIndex == 0){ tempIndex = 0 }; if (monthIndex == 1){ tempIndex = 1 }; if (monthIndex == 2){ tempIndex = 2 }; if (monthIndex == 3){ tempIndex = 3 }; if (monthIndex == 4){ tempIndex = 4 }; if (monthIndex == 5){ tempIndex = 5 }; if (monthIndex == 6){ tempIndex = 6 }; if (monthIndex == 7){ tempIndex = 7 }; if (monthIndex == 8){ tempIndex = 8 }; if (monthIndex == 9){ tempIndex = 9 }; if (monthIndex == 10){ tempIndex = 10 }; if (monthIndex == 11){ tempIndex = 11 }; if (tempIndex > -1) { this.monthName = (shorten) ? monthsNames[tempIndex].substring(0, 3) : monthsNames[tempIndex]; } else { this.monthName = ""; } return this.monthName; };

Nota: simplemente incluya las funciones de prototype anteriores en su JS Script y utilícelas como se describe a continuación.

Y siempre que haya una fecha de JS , necesito generar la fecha con la fecha ordinal. Utilizo ese método de prototipo como se indica a continuación en esa fecha de JS :

var myDate = new Date(); // You may have to check your JS Console in the web browser to see the following console.log("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear()); // or I will update the Div. using jQuery $(''#date'').html("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());

E imprimirá la fecha con la fecha ordinal como se muestra en la siguiente demostración en vivo :

Date.prototype.getMonthName = function(shorten) { var monthsNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var monthIndex = this.getMonth(); var tempIndex = -1; if (monthIndex == 0){ tempIndex = 0 }; if (monthIndex == 1){ tempIndex = 1 }; if (monthIndex == 2){ tempIndex = 2 }; if (monthIndex == 3){ tempIndex = 3 }; if (monthIndex == 4){ tempIndex = 4 }; if (monthIndex == 5){ tempIndex = 5 }; if (monthIndex == 6){ tempIndex = 6 }; if (monthIndex == 7){ tempIndex = 7 }; if (monthIndex == 8){ tempIndex = 8 }; if (monthIndex == 9){ tempIndex = 9 }; if (monthIndex == 10){ tempIndex = 10 }; if (monthIndex == 11){ tempIndex = 11 }; if (tempIndex > -1) { this.monthName = (shorten) ? monthsNames[tempIndex].substring(0, 3) : monthsNames[tempIndex]; } else { this.monthName = ""; } return this.monthName; }; Date.prototype.getDateWithDateOrdinal = function() { var d = this.getDate(); // from here on I''ve used Kennebec''s answer, but improved it. if(d>3 && d<21) return d+''th''; switch (d % 10) { case 1: return d+"st"; case 2: return d+"nd"; case 3: return d+"rd"; default: return d+"th"; } }; var myDate = new Date(); // You may have to check your JS Console in the web browser to see the following console.log("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear()); // or I will update the Div. using jQuery $(''#date'').html("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="date"></p>

.


Fuertemente inspirado en @ user2309185 ''s.

const ordinal = (d) => { return d + ([''st'', ''nd'', ''rd''][d % 10 - 1] || ''th'') }


Implementación funcional super simple:

const ordinal = (d) => { const nth = { ''1'': ''st'', ''2'': ''nd'', ''3'': ''rd'' } return `${d}${nth[d] || ''th''}` } const monthNames = [''January'',''February'',''March'',''April'',''May'',''June'',''July'',''August'',''September'',''October'',''November'',''December''] const dateString = (date) => `${ordinal(date.getDate())} ${monthNames[date.getMonth()]} ${date.getFullYear()}` // Use like this: dateString(new Date()) // 18th July 2016


Llego un poco tarde a la fiesta, pero esto debería funcionar:

function ordinal(number) { number = Number(number) if(!number || (Math.round(number) !== number)) { return number } var signal = (number < 20) ? number : Number(('''' + number).slice(-1)) switch(signal) { case 1: return number + ''st'' case 2: return number + ''nd'' case 3: return number + ''rd'' default: return number + ''th'' } } function specialFormat(date) { // add two weeks date = new Date(+date + 12096e5) var months = [ ''January'' , ''February'' , ''March'' , ''April'' , ''May'' , ''June'' , ''July'' , ''August'' , ''September'' , ''October'' , ''November'' , ''December'' ] var formatted = ordinal(date.getDate()) formatted += '' '' + months[date.getMonth()] return formatted + '' '' + date.getFullYear() } document.body.innerHTML = specialFormat(new Date())


Muchas respuestas de formateo, así que trabajaré en la novena parte de cualquier entero

Number.prototype.nth= function(){ if(this%1) return this; var s= this%100; if(s>3 && s<21) return this+''th''; switch(s%10){ case 1: return this+''st''; case 2: return this+''nd''; case 3: return this+''rd''; default: return this+''th''; } }


Muchas respuestas, aquí hay otra:

function addOrd(n) { var ords = [,''st'',''nd'',''rd'']; var ord, m = n%100; return n + ((m > 10 && m < 14)? ''th'' : ords[m%10] || ''th''); } // Return date string two weeks from now (14 days) in // format 13th March 2013 function formatDatePlusTwoWeeks(d) { var months = [''January'',''February'',''March'',''April'',''May'',''June'', ''July'',''August'',''September'',''October'',''November'',''December'']; // Copy date object so don''t modify original var e = new Date(d); // Add two weeks (14 days) e.setDate(e.getDate() + 14); return addOrd(e.getDate()) + '' '' + months[e.getMonth()] + '' '' + e.getFullYear(); } alert(formatDatePlusTwoWeeks(new Date(2013,2,13))); // 27th March 2013


También lo estaba haciendo para las fechas, pero como el día del mes solo puede estar entre el 1 y el 31, terminé con una solución simplificada.

function dateOrdinal(dom) { if (dom == 31 || dom == 21 || dom == 1) return dom + "st"; else if (dom == 22 || dom == 2) return dom + "nd"; else if (dom == 23 || dom == 3) return dom + "rd"; else return dom + "th"; };

o versión compacta utilizando operadores condicionales.

function dateOrdinal(d) { return d+(31==d||21==d||1==d?"st":22==d||2==d?"nd":23==d||3==d?"rd":"th") };

http://jsben.ch/#/DrBpl


Una solución corta y compacta:

function format(date, tmp){ return [ (tmp = date.getDate()) + ([, ''st'', ''nd'', ''rd''][/1?.$/.exec(tmp)] || ''th''), [ ''January'', ''February'', ''March'', ''April'', ''May'', ''June'', ''July'', ''August'', ''September'', ''October'', ''November'', ''December'' ][date.getMonth()], date.getFullYear() ].join('' '') } // 14 days from today console.log(''14 days from today: '' + format(new Date(+new Date + 14 * 864e5))); // test formatting for all dates within a month from today var day = 864e5, today = +new Date; for(var i = 0; i < 32; i++) { console.log(''Today + '' + i + '': '' + format(new Date(today + i * day))) }

(El enfoque compacto basado en expresiones regulares para obtener el sufijo ordinal appears several places la web, se desconoce la fuente original)


Date.prototype.getMonthName = function(shorten) { var monthsNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var monthIndex = this.getMonth(); var tempIndex = -1; if (monthIndex == 0){ tempIndex = 0 }; if (monthIndex == 1){ tempIndex = 1 }; if (monthIndex == 2){ tempIndex = 2 }; if (monthIndex == 3){ tempIndex = 3 }; if (monthIndex == 4){ tempIndex = 4 }; if (monthIndex == 5){ tempIndex = 5 }; if (monthIndex == 6){ tempIndex = 6 }; if (monthIndex == 7){ tempIndex = 7 }; if (monthIndex == 8){ tempIndex = 8 }; if (monthIndex == 9){ tempIndex = 9 }; if (monthIndex == 10){ tempIndex = 10 }; if (monthIndex == 11){ tempIndex = 11 }; if (tempIndex > -1) { this.monthName = (shorten) ? monthsNames[tempIndex].substring(0, 3) : monthsNames[tempIndex]; } else { this.monthName = ""; } return this.monthName; }; Date.prototype.getDateWithDateOrdinal = function() { var d = this.getDate(); // from here on I''ve used Kennebec''s answer, but improved it. if(d>3 && d<21) return d+''th''; switch (d % 10) { case 1: return d+"st"; case 2: return d+"nd"; case 3: return d+"rd"; default: return d+"th"; } }; var myDate = new Date(); // You may have to check your JS Console in the web browser to see the following console.log("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear()); // or I will update the Div. using jQuery $(''#date'').html("date with date ordinal: "+myDate.getDateWithDateOrdinal()+" "+myDate.getMonthName()+" "+myDate.getFullYear());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="date"></p>