我想检查 08/2014 是否大于 02/2014。
我该如何在Javascript中实现呢?有人能帮帮我吗...
目前我只检查未来的年份。以下是代码片段:
this.isDateGreaterThanCurrent=function(b){
return parseInt(b)>parseInt(new Date().getFullYear());
};
我想检查 08/2014 是否大于 02/2014。
我该如何在Javascript中实现呢?有人能帮帮我吗...
目前我只检查未来的年份。以下是代码片段:
this.isDateGreaterThanCurrent=function(b){
return parseInt(b)>parseInt(new Date().getFullYear());
};
使用moment.js(我推荐的),然后..
var d1 = moment("08/2014", "MM/YYYY")
var d2 = moment("02/2014", "MM/YYYY")
d1.isBefore(d2) // false
d1.isAfter(d2) // true
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
Date
对象可以相互比较。因此,您可以直接使用date
对象而无需解析它们。
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"))
new Date(year, month) //month start from 0 (ie january is 0)
作为,
d1 = new Date(2014, 7) // 08/2014 (month - 1)
d2 = new Date(2014, 1) // 02/2014
现在进行检查,
Date.parse(d1) > Date.parse(d2)
Date.parse()
解析一个日期的字符串表示,并返回自1970年1月1日00:00:00以来的毫秒数,本地时间。
你快要完成了...使用split方法将你的日期创建为一个数组
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;
};
function checkMonths(month1, month2) {
var m1 = month1.split("/");
var m2 = month2.split("/");
var res = -1;
if( parseInt(m1[1] ) > parseInt(m2[1]) ) {
res = 1;
} else if(parseInt(m1[1] ) == parseInt(m2[1])) {
if(parseInt(m1[0] ) > parseInt(m2[0])) {
res = 1;
} else if(parseInt(m1[0] ) == parseInt(m2[0])) {
res = 0;
}
}
return res;
}
工作演示 JSFiddle演示
moment("08/2014", "MM/YYYY").isBefore(moment("02/2014", "MM/YYYY"))
。不过,你也可以手动完成这个任务。我会先创建一个函数,将输入的"02/2014"转换为"2014-02"格式,然后再与标准字符串进行字典序比较。 - user2864740