Javascript比较两个日期,从字符串开始< = end [英] Javascript to compare two dates, from strings, begin <= end
问题描述
我的验证开始于< = end
Date.new(begin)即使在ISO上生成无效日期!
不要使用 Date.new
。使用 new Date()
。由于日期字符串的格式,我建议您单独抓取每个字段并将其传递到构造函数中:
var startYear = parseInt(document.getElementById('startYear'),10);
var startMonth = parseInt(document.getElementById('startMonth'),10) - 1; //根据Residuum的注释
var startDay = parseInt(document.getElementById('startDay'),10);
var start = new日期(startYear,startMonth,startDay);
等。如果你提交了一个日期字符串,那么你可以使用模糊棒棒糖的方法从字符串中获取每个字段。我不知道Date构造函数是否会接受各个字段的解析字符串。
一旦你有两个日期,你想比较,只是比较它们的价值,以毫秒为单位:
function isValid(start,end){
return start.getTime () end.getTime();
}
I get two strings formated like (Brazilian Format): "DD/MM/YYYY", I need to compare both. Since the first field is the begin and the last is the end,
My validation is begin <= end
Date.new(begin) is generating 'invalid date' even on ISO !
Don't use Date.new
. Use new Date()
. Because of the format of your date string, I would recommend grabbing each field individually and passing them into the constructor:
var startYear = parseInt(document.getElementById('startYear'), 10);
var startMonth = parseInt(document.getElementById('startMonth'), 10) - 1; // as per Residuum's comment
var startDay = parseInt(document.getElementById('startDay'), 10);
var start = new Date(startYear, startMonth, startDay);
etc. If you're handed a date string, then you can use fuzzy lollipop's method to get each field from the string. I'm not sure if the Date constructor will accept unparsed strings for the individual fields, however.
The, once you have the two dates you'd like to compare, just compare their values in milliseconds since the epoch:
function isValid(start, end) {
return start.getTime() < end.getTime();
}
这篇关于Javascript比较两个日期,从字符串开始< = end的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!