有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。
当前回答
为了在众多现有选项中添加另一种可能性,您可以尝试:
if (date1.valueOf()==date2.valueOf()) .....
…这似乎对我有用。当然,你必须确保这两个日期都没有定义。。。
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....
通过这种方式,我们可以确保如果两者都未定义,或者。。。
if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....
…如果你希望他们不平等。
其他回答
比较两个日期的一种方法是使用dates.js库。
Date.compare(Date-date1,Date-date2)方法,返回一个数字,表示以下结果之一:
-1=日期1小于日期2。0=值相等。1=日期1大于日期2。
为了从JavaScript中的自由文本创建日期,您需要将其解析为Date对象。
您可以使用Date.parse(),它获取自由文本并尝试将其转换为新的日期,但如果您能够控制页面,我建议使用HTML选择框或日期选择器,例如YUI日历控件或jQueryUI日期选择器。
正如其他人所指出的,一旦你有了日期,你就可以使用简单的算术来减去日期,并将其转换为天数,方法是将数字(以秒为单位)除以一天中的秒数(60*60*24=86400)。
function compare_date(date1, date2){
const x = new Date(date1)
const y = new Date(date2)
function checkyear(x, y){
if(x.getFullYear()>y.getFullYear()){
return "Date1 > Date2"
}
else if(x.getFullYear()<y.getFullYear()){
return "Date2 > Date1"
}
else{
return checkmonth(x, y)
}
}
function checkmonth(x, y){
if(x.getMonth()>y.getFullYear()){
return "Date1 > Date2"
}
else if(x.getMonth()<y.getMonth){
return "Date2 > Date1"
}
else {
return checkDate(x, y)
}
}
function checkDate(x, y){
if(x.getDate()>y.getFullYear()){
return "Date1 > Date2"
}
else if(x.getDate()<y.getDate()){
return "Date2 > Date1"
}
else {
return checkhour(x,y)
}
}
function checkhour(x, y){
if(x.getHours()>y.getHours()){
return "Date1 > Date2"
}
else if(x.getHours()<y.getHours()){
return "Date2 > Date1"
}
else {
return checkhmin(x,y)
}
}
function checkhmin(x,y){
if(x.getMinutes()>y.getMinutes()){
return "Date1 > Date2"
}
else if(x.getMinutes()<y.getMinutes()){
return "Date2 > Date1"
}
else {
return "Date1 = Date2"
}
}
return checkyear(x, y)
使用momentjs进行日期操作。
使用
isSameOrAfter()方法
moment('2010-10-20').isSameOrAfter('2010-10-20') //true;
使用isAfter()方法检查一个日期是否在另一个日期之后
moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true
使用isBefore()方法检查一个日期是否早于另一个日期。
moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false
使用isSame()方法检查一个日期与另一个日期是否相同
moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true
减去两个日期,得到以毫秒为单位的差值,如果得到0,则是相同的日期
function areSameDate(d1, d2){
return d1 - d2 === 0
}
推荐文章
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在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文件夹的作用是什么?