Reputation: 51
I have to retrieve the year from date string. the date string format should be any of the following formats. I need to globalized code to retrieve the year in any date string formats.
Date formats, "30/8/2013","08/30/2013",30-8-2013","2013-08-30","30.8.2013","30-08-13","13-08-30" etc.
Upvotes: 1
Views: 557
Reputation: 1061
try like this
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);
Upvotes: 0
Reputation: 1092
01-02-03 could be 2001-02-03 or 01-02-2003, it is impossible to make sure if you don't have other restriction.
For "30/8/2013","08/30/2013",30-8-2013","2013-08-30","30.8.2013", you can use this regex:
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);
which outputs:
["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
Upvotes: 0
Reputation: 9904
Take a look at this library. http://momentjs.com/
This is probably your best option available.
Upvotes: 1