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">
Ren
  • 1,493
  • 6
  • 31
  • 56

1 Answers1

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.

Community
  • 1
  • 1
RyanJM
  • 7,028
  • 8
  • 60
  • 90
  • Thanks !! All working now. Does new Date() or parseDate take an additional parameter to specify the format of the date string ? – Ren Mar 12 '14 at 17:38
  • Unfortunately no. If you are going to be doing a lot with dates [moment js](http://momentjs.com/) is a really good library to have around. – RyanJM Mar 12 '14 at 17:42
  • Yeah. I've been just going through its site, and it looks very good.. Thanks for your help.. – Ren Mar 12 '14 at 17:47
  • No problem. In my answer I added a link to the parse method which does what you were talking about. – RyanJM Mar 12 '14 at 17:50