Reputation: 1503
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">
Upvotes: 0
Views: 1364
Reputation: 7068
@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.
Upvotes: 2