转换日期日(2011年12月5日至12日)

时间:2011-05-14 17:20:58

标签: javascript date

我试图将日期转换为天数,然后是“st”,“nd”,“rd”或“th取决于当天。我是javascript的新手,所以不知道从哪里开始。

E.g。

05/01/2011 =第1年 05/02/2011 =第2年 05/03/2011 =第3年 05/12/2011 = 12th
05/22/2011 = 22nd

由于

5 个答案:

答案 0 :(得分:10)

首先,获取日期:

 var date = myval.getDate();

然后找到后缀:

 function get_nth_suffix(date) {
   switch (date) {
     case 1:
     case 21:
     case 31:
        return 'st';
     case 2:
     case 22:
        return 'nd';
     case 3:
     case 23:
        return 'rd';
     default:
        return 'th';
   }
 }

演示http://jsfiddle.net/DZPSw/

答案 1 :(得分:9)

var date = new Date('05/12/2011').getDate(),
 ordinal = date + (date>10 && date<20 ? 'th' : {1:'st', 2:'nd', 3:'rd'}[date % 10] || 'th');

ordinal = date + ( [,'st','nd','rd'][/1?.$/.exec(date)] || 'th' );

答案 2 :(得分:2)

您可以从JavaScript Date/Time Functions开始获取日期编号:

var theDate = myDateObj.GetDate(); // returns 1-31

然后,您需要编写规则以获取正确的后缀。除了例外情况,大部分时间它都是th。有什么例外? 1,21,31 = st,2,22 = nd,3,23 = rd,其他所有内容均为th。因此,我们可以使用mod %来检查它是以1,2还是3结尾:

var nth = '';
if (theDate > 3 && theDate < 21)    // catch teens, which are all 'th'
    nth = theDate + 'th';
else if (theDate % 10 == 1)         // exceptions ending in '1'
    nth = theDate + 'st';
else if (theDate % 10 == 2)         // exceptions ending in '2'
    nth = theDate + 'nd';
else if (theDate % 10 == 3)         // exceptions ending in '3'
    nth = theDate + 'rd';
else
    nth = theDate + 'th';           // everything else

这是一个显示1-31结尾的工作演示:http://jsfiddle.net/6Nhn8/

或者你可能会很无聊和use a library: - )

答案 3 :(得分:1)

前几天我写了这个简单的功能。虽然对于一个日期你不需要更大的数字,这也将迎合更高的值(1013th,36021st等...)

var fGetSuffix = function(nPos){

    var sSuffix = "";

    switch (nPos % 10){
        case 1:
            sSuffix = (nPos % 100 === 11) ? "th" : "st";
            break;
        case 2:
            sSuffix = (nPos % 100 === 12) ? "th" : "nd";
            break;
        case 3:
            sSuffix = (nPos % 100 === 13) ? "th" : "rd";
            break;
        default:
            sSuffix = "th";
            break;
    }

    return sSuffix;
};

答案 4 :(得分:0)

您可以使用S datejs format specifier轻松完成此操作。

相关问题