有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。
当前回答
注意-仅比较日期部分:
当我们在javascript中比较两个日期时。这需要数小时、数分钟和数秒的时间。。因此,如果我们只需要比较日期,这是一种方法:
var date1= new Date("01/01/2014").setHours(0,0,0,0);
var date2= new Date("01/01/2014").setHours(0,0,0,0);
现在:如果date1.valueOf()>date2.valueOf。
其他回答
试试这个而比较日期应为iso格式“yyyy-MM-dd”如果要仅比较日期,请使用此datehelper
<a href="https://plnkr.co/edit/9N8ZcC?p=preview"> Live Demo</a>
嗨,这是我比较日期的代码。在我的情况下,我正在检查是否允许选择过去的日期。
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;
var date = new Date(); // will give you todays date.
// following calls, will let you set new dates.
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
var yesterday = new Date();
yesterday.setDate(...date info here);
if(date>yesterday) // will compare dates
注意时区
javascript日期没有时区的概念。这是一个时刻(从大纪元开始计时),具有方便的函数,用于在“本地”时区中转换字符串。如果您想使用日期对象处理日期,正如这里的每个人所做的那样,您希望您的日期在所讨论的日期开始时表示UTC午夜。这是一个常见且必要的惯例,允许您处理日期,而不考虑创建日期的季节或时区。因此,您需要非常警惕地管理时区的概念,尤其是在创建午夜UTC日期对象时。
大多数时候,您都希望您的日期反映用户的时区。如果今天是你的生日,请单击。新西兰和美国的用户同时点击并获得不同的日期。在这种情况下,这样做。。。
// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));
有时,国际可比性胜过本地准确性。在这种情况下,这样做。。。
// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCYear(), myDate.getyUTCMonth(), myDate.getUTCDate()));
现在你可以像其他答案所建议的那样直接比较你的约会对象。
在创建时注意管理时区,在转换回字符串表示形式时还需要确保将时区排除在外。因此,您可以安全地使用。。。
到ISOString()getUTCxxx()getTime()//返回一个没有时间或时区的数字。.toLocaleDateString(“fr”,{timezone:“UTC”})//任何您想要的语言环境,但始终是UTC。
完全避免其他一切,特别是。。。
getYear()、getMonth()和getDate()
什么格式?
如果您构造了Javascript Date对象,您可以将它们减去以获得毫秒差(编辑:或只是比较它们):
js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true