web-dev-qa-db-ja.com

JavaScriptの新しい日付序数(st、nd、rd、th)

可能であれば、JavaScriptライブラリや大量の不格好なコードなしで、2週間後の日付を次の形式でフォーマットする最も簡単な方法を探しています。

13th March 2013

私が使用しているコードは次のとおりです。

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

これは、2週間後の日付と時刻を返しますが、次のようになります:Wed Mar 27 2013 21:50:29 GMT + 0000(GMT Standard Time)

jsFiddle のコードは次のとおりです。

助けていただければ幸いです!

36
user1635828

ここに:

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

他の回答に触発されたライナーがあります。テストされ、0と負の数を取ります。

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

書式設定の答えがたくさんあるので、整数の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';
    }
}
4
kennebec

私は日付に対してもこれを行っていましたが、月の日は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

2
fredli74

たくさんの答え、ここに別のものがあります:

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

多くの人が言及しているように、別の答えがあります。

これは@ kennebecの回答に直接基づいています。これは、このdate Ordinalを特定のJavaScript日付:

次のように2つの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;
};

注:JS Script内に上記のprototype関数を含めるだけで、以下の説明に従って使用します。

そして、JSdateがある場合はいつでも、日付序数で日付を生成する必要があります。その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());

そして、以下のlive demoに示すようにdate ordinalで日付を出力します:

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

人間が読めるバージョン...

0
Matt Claffey

短くコンパクトなソリューション:

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

(順序サフィックスを取得するためのコンパクトな正規表現ベースのアプローチ 表示複数場所 Webの周り、元のソースは不明)

0
Tomas Langkaas

私はパーティーに少し遅れていますが、これはうまくいくはずです:

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