Reputation: 103
I'm trying to write a piece of code similar to below in AngularJS:
$scope.isAfterToday= function(inputDate){
if(inputDate > Date.now().toString()){
return true;
} else {
return false;
}
}
However, the problem is that the parameter inputDate comes in the format "2016-10-12T00:00:00" which is different than the format that comes out of the Date.now() function. Is there an easy way to convert between these two formats other than brute force of parsing out the month, day, and year from each and comparing the two?
Thank you for any help!
Upvotes: 0
Views: 1143
Reputation: 2379
$scope.isAfterToday=function(inputDate){
//First get the first time *after* today:
var t = new Date().setHours(0,0,0,0);//0 seconds into this morning
t.setDate(t.getDate()+1); //midnight tomorrow
new Date(inputDate) > t );
};
No external library necessary. You can compare Date
objects directly, and the Date
constructor accepts a variety of date format strings as input.
For Date
object comparisons, you can use common numeric comparators:
<
>
<=
>=
Don't use ==
though, it will compare their object references instead of their values.
Upvotes: 1
Reputation: 360
You can use the Date object to convert your inputDate into a number of milliseconds that you can compare.
var convertedInput = new Date(inputDate);
If you need to go the other way and output something that looks nice, there's technically no formatted output. But parsing milliseconds into dates isn't all that hard!
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1; //Month is 0-based for some reason
var year = today.getFullYear();
var datenow = year + "-" + month + "-" + day;
Upvotes: 0
Reputation: 1477
You can wrap the inputDate in standard Date object, like this:
new Date("2016-10-12T00:00:00").getTime(); // you'll get 1476230521000
And new Date().toISOString();
to reverse
Upvotes: 0