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

时间:2013-03-13 22:02:51

标签: javascript date ordinal-indicator

如果可能的话,没有JavaScript库或大量笨重的代码,我正在寻找最简单的方法来格式化一个日期,从现在起以下列格式:

13th March 2013

我使用的代码是:

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

从现在起两周后返回日期和时间,但是像这样: 2013年3月27日星期三21:50:29 GMT + 0000(格林威治标准时间标准时间)

以下是jsFiddle中的代码。

任何帮助将不胜感激!

17 个答案:

答案 0 :(得分:61)

下面:

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

答案 1 :(得分:17)

这是一个受其他答案启发的单线。它经过测试,将采用0和负数。

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

答案 2 :(得分:3)

很多格式化答案,所以我只会处理任何整数的第n个 -

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 :(得分:2)

这是一个适用于任何数字的简单函数:

function getOrdinal(n) {
    let ord = ["st", "nd", "rd"]
    let exceptions = [11, 12, 13]
    let nth = 
    ord[(n % 10) - 1] == undefined || exceptions.includes(n % 100) ? "th" : ord[(n % 10) - 1]
    return n + nth
}

它可以接受数字或数字作为字符串。例如:

getOrdinal(28)        //Outputs: 28th
getOrdinal('108')     //Outputs: 108th

答案 4 :(得分:2)

我也是这样做的日期,​​但由于月份的日期只能在1到31之间,我最终得到了一个简化的解决方案。

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

或使用条件运算符的紧凑版本

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

答案 5 :(得分:1)

很多答案,这是另一个答案:

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

答案 6 :(得分:1)

如果您是moment.js的粉丝,那么可以使用format(“ Do”)

示例

var newdate = new Date();
moment(newdate).format("Do MMMM YYYY")
//Returns 1st January 2020

moment("01/01/2020", "MM/DD/YYYY").format("Do")
//Returns 1st

moment("01/01/2020", "MM/DD/YYYY").format("Do MMM YYYY")
//Returns 1st Jan 2020

答案 7 :(得分:0)

这是一个可读的 ES+ 版本。

Player 1 2 Selections:<br />10,3<br /><br />
Player 2 2 Selections:<br />4,5<br /><br />
Player 3 2 Selections:<br />2,7<br /><br />
Player 4 2 Selections:<br />1,6<br /><br />
Player 5 2 Selections:<br />8,9<br /><br />

答案 8 :(得分:0)

解决方案海洋中的另一种解决方案。

let suffix = (day >= 4 &&  day <= 20) || (day >= 24 && day <= 30)
    ? "th"
    : ["st", "nd", "rd"][day % 10 - 1];

答案 9 :(得分:0)

function getSuffixForDate(day) {
  const lastNumberOfTheDay = day[day.length];

  const suffixes = {
    1: () => 'st',
    21: () => 'st',
    31: () => 'st',
    2: () => 'nd',
    22: () => 'nd',
    3: () => 'rd',
    23: () => 'rd',
  };

  return suffixes[lastNumberOfTheDay] !== undefined ? `${day}${suffixes[lastNumberOfTheDay]()}` : `${day}th`;
}

const date = new Date();
const formattedDate = `${getSuffixForDate(date.getDate())} ${monthNames[date.getMonth()]} ${date.getFullYear()}`;

人类可读的版本...

答案 10 :(得分:0)

	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>

答案 11 :(得分:0)

简短而紧凑的解决方案:

&#13;
&#13;
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)))
}
&#13;
&#13;
&#13;

(基于正则表达式的紧凑型方法,用于在网络上获取序数后缀appears several places,原始来源未知)

答案 12 :(得分:0)

正如许多人所提到的,这是另一个答案。

这是直接基于 @kennebec 的答案,我找到了为给定{{1}生成日期序数的最简单方法} date:

我创建了两个JavaScript,如下所示:

prototype function

注意:只需在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; }; 中添加上述prototype个功能,然后按照下文所述使用它。

只要有JS Script 日期,我需要生成日期序号的日期我在JS 日期使用原型方法如下:< /强>

JS

它将使用 date ordinal 打印出日期,如以下现场演示所示:

&#13;
&#13;
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());
&#13;
	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());
&#13;
&#13;
&#13;

答案 13 :(得分:0)

我参加派对有点晚了,但这应该有效:

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

答案 14 :(得分:-1)

这是一个简单的解决方案:

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

答案 15 :(得分:-1)

受到 @ user2309185 的强烈启发。

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

答案 16 :(得分:-1)

超级简单的功能实现:

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