有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。
当前回答
尝试使用此代码
var f =date1.split("/");
var t =date2.split("/");
var x =parseInt(f[2]+f[1]+f[0]);
var y =parseInt(t[2]+t[1]+t[0]);
if(x > y){
alert("date1 is after date2");
}
else if(x < y){
alert("date1 is before date2");
}
else{
alert("both date are same");
}
其他回答
关系运算符<<=>>=可用于比较JavaScript日期:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 < d2; // true
d1 <= d2; // true
d1 > d2; // false
d1 >= d2; // false
然而,等式运算符==!===!==无法用于比较(的值)日期,因为:
对于严格或抽象的比较,两个不同的对象永远不相等。只有当操作数引用同一对象时,比较对象的表达式才为真。
您可以使用以下任一方法比较相等的日期值:
var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
/*
* note: d1 == d2 returns false as described above
*/
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1) == Number(d2); // true
+d1 == +d2; // true
Date.getTime()和Date.valueOf()都返回自1970年1月1日00:00UTC以来的毫秒数。Number函数和一元+运算符都在幕后调用valueOf()方法。
嗨,这是我比较日期的代码。在我的情况下,我正在检查是否允许选择过去的日期。
var myPickupDate = <pick up date> ;
var isPastPickupDateSelected = false;
var currentDate = new Date();
if(currentDate.getFullYear() <= myPickupDate.getFullYear()){
if(currentDate.getMonth()+1 <= myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
if(currentDate.getDate() <= myPickupDate.getDate() || currentDate.getMonth()+1 < myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
isPastPickupDateSelected = false;
return;
}
}
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;
我对这个问题的简单回答
checkDisabled(date) {
const today = new Date()
const newDate = new Date(date._d)
if (today.getTime() > newDate.getTime()) {
return true
}
return false
}
另一种比较两个日期的方法是通过toISOString()方法。这在与保存在字符串中的固定日期进行比较时特别有用,因为可以避免创建短时间对象。借助ISO 8601格式,您可以按字典方式比较这些字符串(至少在使用相同时区时)。
我不一定说它比使用时间对象或时间戳更好;只是将此作为另一种选择。这可能会失败,但我还没有发现:)
为了从JavaScript中的自由文本创建日期,您需要将其解析为Date对象。
您可以使用Date.parse(),它获取自由文本并尝试将其转换为新的日期,但如果您能够控制页面,我建议使用HTML选择框或日期选择器,例如YUI日历控件或jQueryUI日期选择器。
正如其他人所指出的,一旦你有了日期,你就可以使用简单的算术来减去日期,并将其转换为天数,方法是将数字(以秒为单位)除以一天中的秒数(60*60*24=86400)。
推荐文章
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 单元测试:日期时间。现在
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标