1

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.

3
  • This is code,var reg = /(yyyy)|(yy)/; var formattedDt = "30/08/2013"; //"30-08-2013","30.08.2013","08.30.13" etc., var minYear = ""; formattedDt = formattedDt.replace(reg, minYear); alert(minYear); Commented Sep 3, 2013 at 6:42
  • w3resource.com/javascript/object-property-method/… Commented Sep 3, 2013 at 6:49
  • 1
    how would you differentiate if date comes as 13-09-13? do you also have format stored somewhere like yy-mm-dd? Commented Sep 3, 2013 at 6:51

3 Answers 3

1

Take a look at this library. http://momentjs.com/

This is probably your best option available.

Sign up to request clarification or add additional context in comments.

1 Comment

You can parse date string of any format using moment.js. Once you parse it, getting a year is trivial like this m.year();
0

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

2 Comments

thanks, it is displayed the 2013/8/30,2013,. I want only the year value. help me.
Please check it. the 30-08-13 case it is not working. jsfiddle.net/45PNy/1
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.