0

I have two strings in mm-yyyy format (eg: 05-2012) and I need to compare them.

I tried using $filter and Date.parse, but no luck thus far. I don't want to append the string with a dummy 'day' part, unless there is no other way.

Below is my code. Any help would be much appreciated. Thanks.

    var date1= $filter('text')($scope.date1, "mm-yyyy");
    var date2= $filter('text')($scope.date2, "mm-yyyy");
    if (date2 <= date1) {
        $scope.hasInvalidDate = true;
    }

    <input type="text" ng-model="date1" placeholder="mm-yyyy">
    <input type="text" ng-model="date2" placeholder="mm-yyyy">
2
  • Split them by "-", reverse, join with "-", compare Commented Mar 12, 2014 at 17:17
  • Thanks. will give it a go now. Commented Mar 12, 2014 at 17:22

1 Answer 1

2

@SmokeyPHP is right, you can do this with JS. See this SO question.

function parseDate(input) {
  var parts = input.split('-');
  // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[1], parts[0]-1); // Note: months are 0-based
}

> parseDate("05-2012")
Tue May 01 2012 00:00:00 GMT-0600 (MDT)

And you have the compare part correct.

> d1 = parseDate("05-2012")
Tue May 01 2012 00:00:00 GMT-0600 (MDT)
> d2 = parseDate("06-2012")
Fri Jun 01 2012 00:00:00 GMT-0600 (MDT)
> d1 < d2
true

If you do a lot with dates in JS then moment js is worth looking at. Specifically in this case it has a parse method which can take a format string.

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

4 Comments

Thanks !! All working now. Does new Date() or parseDate take an additional parameter to specify the format of the date string ?
Unfortunately no. If you are going to be doing a lot with dates moment js is a really good library to have around.
Yeah. I've been just going through its site, and it looks very good.. Thanks for your help..
No problem. In my answer I added a link to the parse method which does what you were talking about.

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.