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

前端 未结 15 1925
北海茫月
北海茫月 2020-11-27 03:12

If at all possible, without JavaScript libraries or lots of clunky code I am looking for the simplest way to format a date two weeks from now in the following format:

<
15条回答
  •  -上瘾入骨i
    2020-11-27 03:54

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

提交回复
热议问题