简体   繁体   English

怎么写有条件的时间?

[英]How to write a conditional for a time?

I'm trying to get a conditional what with the date of tomorrow example let me know what if is tomorrow and is more than 1pm of tomorrow so do something. 我正在尝试获取有条件的明天日期示例,让我知道明天是下午1点多,该做什么。

I work with MomentJs, so if you have a solution with this that can help me, is appreciated. 我与MomentJs合作,因此,如果您有一个可以帮助我的解决方案,我们将不胜感激。

In momentJS, you can get tomorrow by 在momentJS中,您可以通过

const tomorrow  = moment().add(1, 'days');

If you want to get tomorrow 1.00 PM then 如果您想明天下午1:00

var tomorrow = moment('01:00 pm', "HH:mm a").add(1, 'days');

If you want to compare, then 如果要比较的话

var tomorrow = moment('01:00 pm', "HH:mm a").add(1, 'days');

var current = moment();

if(current < tomorrow)
  console.log('true');
else
  console.log('false');

To get a Date for 13:00 tomorrow, you can create a date for today, add a day, then set the time to 13:00. 要获得明天13:00的日期,您可以为今天创建一个日期,添加一天,然后将时间设置为13:00。

Then you can directly compare it to other dates using comparison operators < and > (but you need to convert both dates to numbers to compare as == or === ). 然后,您可以使用比较运算符<>将其直接与其他日期进行比较(但您需要将两个日期都转换为数字以进行=====比较)。

Eg 例如

 // return true if d0 is before d1, otherwise false function isBefore(d0, d1) { return d0 < d1; } // Generate some sample dates let now = new Date(); let d0 = new Date(now.setDate(now.getDate() + 1)); let d1 = new Date(now.setHours(10)); let d2 = new Date(now.setHours(15)); // Format output function formatDate(d) { let options = {day:'2-digit', month:'short', year:'numeric', 'hour-12':false, hour:'2-digit',minute:'2-digit'}; return d.toLocaleString('en-gb',options); } // Create a test date for 13:00 tomorrow var testDate = new Date(); testDate.setDate(testDate.getDate() + 1); testDate.setHours(13,0,0,0); // Test it against sample dates [d0,d1,d2].forEach(function(d) { console.log(formatDate(d) + ' before ' + formatDate(testDate) + '? ' + isBefore(d, testDate)); }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM