我试图使用momentjs来检查给定的日期是今天还是将来。
这是我目前所拥有的:
<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>
<script type="text/javascript">
var SpecialToDate = '31/01/2014'; // DD/MM/YYYY
var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment().diff(SpecialTo) > 0) {
alert('date is today or in future');
} else {
alert('date is in the past');
}
</script>
代码评估我的日期(2014年1月31日)作为过去的日期。
知道我哪里做错了吗?
更新
moment().isSame('2010-02-01', 'day'); // Return true if we are the 2010-02-01
我后来发现了isSame函数,我认为这是用于确定日期是否为今天的正确函数。
原来的答案
以防别人需要,就这么做:
const isToday = moment(0, "HH").diff(date, "days") == 0;
或者如果你想要一个函数:
isToday = date => moment(0,"HH").diff(date, "days") == 0;
date是要检查的日期。
解释
moment(0,“HH”)在午夜返回今天的日期。
date1。Diff (date2, "days")返回date1和date2之间的天数。
我想用它做别的事情,但最终发现了一个你可以尝试的技巧
somedate。calendar(compareDate, {sameDay: '[Today]'})=='今天'
var d = moment();
var today = moment();
console.log("Usign today's date, is Date is Today? ",d.calendar(today, {
sameDay: '[Today]'})=='Today');
var someRondomDate = moment("2012/07/13","YYYY/MM/DD");
console.log("Usign Some Random Date, is Today ?",someRondomDate.calendar(today, {
sameDay: '[Today]'})=='Today');
var anotherRandomDate = moment("2012/07/13","YYYY/MM/DD");
console.log("Two Random Date are same date ? ",someRondomDate.calendar(anotherRandomDate, {
sameDay: '[Today]'})=='Today');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
如果firstDate相同或在(future) secondDate之后返回true否则返回false。Toda是firstDate = new Date();
static isFirstDateSameOrAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if(date1 && date2){
return date1.isSameOrBefore(date2,'day');
}
return false;
}
有isSame, isBefore和isAfter为日比较时刻的例子;
static isFirstDateSameSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if (date1 && date2) {
return date1.isSame(date2,'day');
}
return false;
}
static isFirstDateAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if(date1 && date2){
return date1.isAfter(date2,'day');
}
return false;
}
static isFirstDateBeforeSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if(date1 && date2){
return date1.isBefore(date2,'day');
}
return false;
}