I want to check if 08/2014 is greater than 02/2014..
How can I do that in Javascript?? Could someone help me please...
Currently I only check for future year. Here is the code snippet.
this.isDateGreaterThanCurrent=function(b){
return parseInt(b)>parseInt(new Date().getFullYear());
};
Date
objects can be compared with each other. So instead of parsing them you can do it as date
object itself.
function isDateGreaterThanToday(b) {
var dS = b.split("/");
var d1 = new Date(dS[1], (+dS[0] - 1));
var today = new Date();
if (d1 > today) {
return "D is greater";
} else {
return "today is greater";
}
}
console.log(isDateGreaterThanToday("08/2014"))
JSFiddle
With moment.js (which I recommend), then ..
var d1 = moment("08/2014", "MM/YYYY")
var d2 = moment("02/2014", "MM/YYYY")
d1.isBefore(d2) // false
d1.isAfter(d2) // true
However, this can be done by hand without much effort.
Create a function that took in "MM/YYYY" and returns "YYYY-MM". The result can then be compared with a standard string compare. The major-first component layout is one reason why a format like ISO 8601 is nice - even as a string, it can be easily ordered.
function toPartialIso(str) {
var m = str.match(/(\d{2})\/(\d{4})/);
if (m) {
return m[2] + "-" + m[1]
}
throw "bad date!"
}
toPartialIso("08/2014") < toPartialIso("02/2014") // false
toPartialIso("08/2014") > toPartialIso("02/2014") // true
construct two date object with
new Date(year, month) //month start from 0 (ie january is 0)
as,
d1 = new Date(2014, 7) // 08/2014 (month - 1)
d2 = new Date(2014, 1) // 02/2014
Now check,
Date.parse(d1) > Date.parse(d2)
Date.parse()
, parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, local time.
You're nearly there ... Using the split method to create an array out of your date
this.isDateGreaterThanCurrent=function(b){
var a = b.split('/');
if(parseInt(a[1])>parseInt(new Date().getFullYear())) return true;
else if (parseInt(a[1]) == parseInt(new Date().getFullYear()) && parseInt(a[0])>parseInt(new Date().getMonth())+1)return true;
else return false;
};
dont forget getMonth returns values from 0 to 11, not from 1 to 12 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With