在开发中,经常需要判断给定日期是否大于当前日期,这时候就需要使用到javascript中的日期比较函数来实现。
javascript中有两种方法可以用来判断给定日期是否大于当前日期:
1.使用 Date.parse() 方法来判断给定日期是否大于当前日期。Date.parse() 方法可以将给定的字符串解析为日期,如果解析成功,则返回一个毫秒数,否则返回NaN。
示例代码:
let currentDate = Date.parse(new Date()); let givenDate = Date.parse('2020-03-01'); if (givenDate > currentDate) { console.log('给定日期大于当前日期'); } else { console.log('给定日期小于等于当前日期'); }
2.使用 Date.getTime() 方法来判断给定日期是否大于当前日期。Date.getTime() 方法可以将 Date 对象转换为毫秒数,再与当前日期的毫秒数进行比较,从而判断给定日期是否大于当前日期。
示例代码:
let currentDate = new Date().getTime(); let givenDate = new Date('2020-03-01').getTime(); if (givenDate > currentDate) { console.log('给定日期大于当前日期'); } else { console.log('给定日期小于等于当前日期'); }
以上就是js判断给定日期是否大于当前日期的方法,通过使用Date.parse()方法和Date.getTime()方法,可以很方便的实现给定日期是否大于当前日期的判断。