JavaScript 新日期序数(st、nd、rd、th)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15397372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:38:52  来源:igfitidea点击:

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

javascriptdateordinal-indicator

提问by user1635828

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:

如果可能的话,没有 JavaScript 库或大量笨重的代码,我正在寻找最简单的方法来格式化两周后的日期,格式如下:

13th March 2013

13th March 2013

The code I am using is:

我正在使用的代码是:

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

which returns the date and time two weeks from now, but like this: Wed Mar 27 2013 21:50:29 GMT+0000 (GMT Standard Time)

它返回两周后的日期和时间,但像这样:Wed Mar 27 2013 21:50:29 GMT+0000(GMT 标准时间)

Here is the code in jsFiddle.

这是jsFiddle 中的代码。

Any help would be appreciated!

任何帮助,将不胜感激!

回答by mplungjan

Here:

这里:

JSFiddle

JSFiddle

const nth = function(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";
  }
}
const fortnightAway = new Date(+new Date + 12096e5);
const date = fortnightAway.getDate();
const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][fortnightAway.getMonth()];

document.getElementById("date").innerHTML = `${date}<sup>${nth(date)}</sup> ${month} ${fortnightAway.getFullYear()}`;
sup {
  font-size: x-small
}
<span id="date"></span>

回答by The Martin

Here is a one liner inspired by the other answers. It is tested and will take 0 and negative numbers.

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

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

回答by kennebec

Lots of formatting answers, so I'll just work on the nth of any integer-

很多格式化答案,所以我只会处理任何整数的第 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';
    }
}

回答by fredli74

I was doing this for dates as well, but because the day of month can only be between 1 and 31, I ended up with a simplified solution.

我也在为日期做这件事,但是因为一个月中的某一天只能在 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";
};

or compact version using conditional operators

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

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

http://jsben.ch/#/DrBpl

回答by RobG

Lots of answers, here's another:

很多答案,这是另一个:

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

回答by Gabe

I'm a bit late to the party, but this should work:

我参加聚会有点晚了,但这应该有效:

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

回答by Randika Vishman

As many has mentioned, here is another answer.

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

This is directly based on @kennebec's answer, which I found the most simplest way to get this date Ordinalgenerated for given JavaScriptdate:

这直接基于@kennebec的答案,我找到了最简单的方法来获取为给定日期生成的此日期顺序JavaScript

I created two prototype functionas follows:

我创建了两个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;
};

Note:just include the above prototypefunctions within your JS Scriptand use it as described bellow.

注意:只需prototype在您的内部包含上述功能JS Script并按如下所述使用它。

And whenever there is a JSdateI need to generate the date with date ordinal I use that prototype method as follows on that JSdate:

每当有一个JS日期我需要生成带有日期序号的日期时,我会在该日期使用该原型方法,如下所示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());

And it will print out date with date ordinalas shown in the following live demo:

它将打印出带有日期序号的日期,如下面的现场演示所示

 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>

.

.

回答by Tomas Langkaas

A short and compact solution:

一个简短而紧凑的解决方案:

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

(The compact regex-based approach for getting the ordinal suffix appearsseveralplacesaround the web, original source unknown)

(用于获取序数后缀的基于正则表达式的紧凑方法出现在网络上的几个地方,原始来源未知)

回答by user3516819

 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>

回答by Matt Claffey

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

A human readable version...

一个人类可读的版本......