web-dev-qa-db-fra.com

JavaScript nouveau Date Ordinal (st, nd, rd, th)

Si possible, sans bibliothèques JavaScript ni beaucoup de code maladroit, je recherche le moyen le plus simple de formater une date dans deux semaines au format suivant:

13th March 2013

Le code que j'utilise est:

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

qui retourne la date et l'heure dans deux semaines, mais comme ceci: mer. 27 mars 2013 21:50:29 GMT + 0000 (heure standard GMT)

Voici le code dans jsFiddle .

Toute aide serait appréciée!

29
user1635828

Ici:

JSFiddle

var fortnightAway = new Date(+new Date + 12096e5),
  date = fortnightAway.getDate(),
  month = ["January","February","March","April","May","June","July",
           "August","September","October","November","December"][fortnightAway.getMonth()];

function nth(d) {
  if (d > 3 && d < 21) return 'th'; 
  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();

56
mplungjan

Voici un one-line inspiré des autres réponses. Il est testé et prendra 0 et des nombres négatifs.

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

Beaucoup de réponses de formatage, donc je vais juste travailler sur le nième de tout

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';
    }
}
3
kennebec

Je le faisais aussi pour les dates, mais comme le jour du mois ne pouvait être qu'entre le 1 et le 31, j’ai obtenu une solution simplifiée.

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";
};

ou version compacte utilisant des opérateurs conditionnels

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

2
fredli74

Beaucoup de réponses, voici une autre:

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
1
RobG

Comme beaucoup l'ont mentionné, voici une autre réponse. 

Ceci est directement basé sur la réponse de @kennebec, que j’ai trouvé le moyen le plus simple d’obtenir cette date ordinale générée pour une JavaScript date donnée:

J'ai créé deux prototype function comme suit:

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;
};

Note: incluez simplement les fonctions prototype ci-dessus dans votre JS Script et utilisez-les comme décrit ci-dessous.

Et chaque fois qu'il y a une JSdate je dois générer la date avec la date ordinale J'utilise cette méthode prototype comme suit pour cette JSdate:

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());

Et il affichera la date avec date ordinale comme indiqué dans la démonstration en direct:

	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>

.

0
Randika Vishman

Une solution courte et compacte:

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

(L’approche compacte basée sur les expressions rationnelles pour obtenir le suffixe ordinal apparaîtplusieurslieux sur le Web, source originale inconnue)

0
Tomas Langkaas

Je suis un peu en retard à la fête, mais ça devrait marcher:

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())
0
Gabe

	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>

0
user3516819