1

我必须从日期字符串中检索年份。日期字符串格式应为以下任一格式。我需要全球化代码以任何日期字符串格式检索年份。

日期格式,"30/8/2013","08/30/2013",30-8-2013","2013-08-30","30.8.2013","30-08-13","13 -08-30" 等

4

3 回答 3

1

看看这个库。http://momentjs.com/

这可能是您最好的选择。

于 2013-09-03T06:39:40.710 回答
0

01-02-03 可能是 2001-02-03 或 01-02-2003,如果没有其他限制则无法确定。

对于 "30/8/2013","08/30/2013",30-8-2013","2013-08-30","30.8.2013",您可以使用此正则表达式:

var pat = /(\d{4})[\-\/\.]\d+[\-\/\.]\d+|\d+[\-\/\.]\d+[\-\/\.](\d{4})/;
r = "30/8/2013".match(pat); console.log(r);
r = "08/30/2013".match(pat); console.log(r);
r = "30-8-2013".match(pat); console.log(r);
r = "2013-08-30".match(pat); console.log(r);
r = "30.8.2013".match(pat); console.log(r);
r = "30-08-13".match(pat); console.log(r);
r = "13-08-30".match(pat); console.log(r);

输出:

["30/8/2013", undefined, "2013", index: 0, input: "30/8/2013"] test.js:2
["08/30/2013", undefined, "2013", index: 0, input: "08/30/2013"] test.js:3
["30-8-2013", undefined, "2013", index: 0, input: "30-8-2013"] test.js:4
["2013-08-30", "2013", undefined, index: 0, input: "2013-08-30"] test.js:5
["30.8.2013", undefined, "2013", index: 0, input: "30.8.2013"] test.js:6
null test.js:7
null test.js:8
于 2013-09-03T06:57:30.733 回答
0

试试这样

var myDate="30.08.2013";

if(myDate.indexOf(".")!= -1){
    var spliter=".";
}else if(myDate.indexOf("/")!= -1){
    var spliter="/";
}
else if(myDate.indexOf("-")!= -1){
    var spliter="-";
}
var year="";
var myDateAray= myDate.split(spliter);
for( i=0;i<myDateAray.length;i++){
    if(myDateAray[i].length > 2){

         year=myDateAray[i];
        break;
    }

    }
alert(year);
于 2013-09-03T07:02:03.700 回答