Roopendra
Roopendra

Reputation: 7776

Need help to extract year from date?

I am using regular expression to match date format. and also extract year, month, date from date. but I am unable to get complete year value here . if I am enter 2013-02-29 than I am getting 20 in year instead of 2013. What I am trying here is :-

$(document).ready(function(){
    var dateVal = '2013-06-01';
    var rxDatePattern = /^(19|20)\d\d(-)(0[1-9]|1[012])(-)(0[1-9]|[12][0-9]|3[01])$/;
    var dtArray = dateVal.match(rxDatePattern);

    dtYear = dtArray[1];
    dtMonth = dtArray[3];
    dtDay = dtArray[5];

    jQuery.each(dtArray, function(index, value) {
        console.log(index + ': ' + value);
    });
}); 

I am getting output :-

0: 2013-06-01

1: 20

2: -

3: 06

4: -

5: 01

here is fiddle : http://jsfiddle.net/roop1886/rYh8N/1/

Here is complete code where I am using above code :-

//varify date formate
jQuery.validator.addMethod(
    "siteDateValidator",
    function (value, element) {
        var currVal = value;
        if (currVal != '') {
            var rxDatePattern = /^(19|20)\d\d(-)(0[1-9]|1[012])(-)(0[1-9]|[12][0-9]|3[01])$/;
            var dtArray = currVal.match(rxDatePattern);
            if (dtArray == null) {
                return false;
            }
            dtYear = (dtArray[1]);
            dtMonth = (dtArray[3]);
            dtDay = (dtArray[5]);

            if (dtMonth < 1 || dtMonth > 12) return false;
            else if (dtDay < 1 || dtDay > 31) return false;
            else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) return false;
            else if (dtMonth == 2) {
                var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
                    if (dtDay > 29 || (dtDay == 29 && !isleap)){
                        return false;
                    }
            }
        }
        return true;
    },
    "Please enter a valid date, date format should be(yyyy-mm-dd) and year should be greater than equal to 1900."
);

Upvotes: 1

Views: 5360

Answers (6)

Nono
Nono

Reputation: 7302

Here is simple answer:

var rxDatePattern = /^(19[\d]{2}|20[\d]{2})(\-)(0[1-9]|1[012])(\-)(0[1-9]|[12][0-9]|3[01])$/;

Upvotes: 1

Rubens Farias
Rubens Farias

Reputation: 57976

What about something like this:

var dateVal  = '2013-06-01';
var parts    = dateVal.match(/(\d{4})-(\d{2})-(\d{2})/)
var testDate = new Date(parts[1], parts[2] - 1, parts[3])
var isFormatValid = parts[1] == testDate.getFullYear()     && // format check
                    parts[2] == testDate.getMonth   () + 1 &&
                    parts[3] == testDate.getDate    ()

var isBusinessValid = isFormatValid && parts[1] >= 1900; // business related 

alert(dateVal + "\n" + testDate + "\n" + isFormatValid + "\n" + isBusinessValid)

In this case, you don't need to deal with full date support in your regex, just extract relevant parts, build a Date object and compare with entered input. Javascript will care about leap years and stuff for you.

Upvotes: 1

user1978104
user1978104

Reputation:

Replace your regular expression you missed grouping for year part. it should be (?:19|20)\d\d) instead of (19|20)\d\d

/^((?:19|20)\d\d)(-)(0[1-9]|1[012])(-)(0[1-9]|[12][0-9]|3[01])$/

Here is working fiddle :- http://jsfiddle.net/roop1886/rYh8N/2/

Upvotes: 1

RobG
RobG

Reputation: 147453

If you want to validate the date and format, you can use:

// Validate date in format yyyy-mm-dd
// Leading zeros on single digit months and days are optional
function validateDate(dateString) {
  var s = dateString.split('-');
  var d = new Date(s[0], --s[1], s[2]);
  return d && d.getFullYear() == s[0] && d.getDate() == s[2];
}

If you want to check that single digit months and days have a leading zero, go for it but I don't see the point.

Upvotes: 0

Adam Hopkinson
Adam Hopkinson

Reputation: 28795

Why not use the build in javascript Date class?

var d = new Date("2013-02-29");
d.getFullYear(); // 2013

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Update: You can detect if the given date was invalid by calling:

var valid = !isNaN(d.getTime()); // returns true if valid, false if invalid

Upvotes: 8

Jaroslav Trsek
Jaroslav Trsek

Reputation: 51

Why don't use split()?

var dateVal = '2013-02-29';
var dtArray = dateVal.split("-");

dtYear = (dtArray[0]);
dtMonth = (dtArray[1]);
dtDay = (dtArray[2]);

alert(dtYear);
alert(dtMonth);
alert(dtDay);

Upvotes: 1

Related Questions