简体   繁体   English

如何在Angular中检查日期是否低于4年?

[英]How to check if the date is below 4 years in Angular?

How can I check if the date in below than 4 years in Angular (JavaScript)? 如何检查Angular(JavaScript)中小于4年的日期?

I would like to show one message if it's true and another message if false. 我想显示一条消息,如果它是true,则显示另一条消息,如果它是false。

I would like to check for specific date for example 08.07.2015 (exactly 4 years from now, to get this date and compare). 我想检查特定的日期,例如08.07.2015(从现在起正好是4年,以便获取该日期并进行比较)。

My code: 我的代码:

 public yearsDif() { const field = this.fForm.get("field").value; let diff = new Date().getFullYear() - new Date(field).getFullYear(); if (diff < 4) { alert('under 4 years'); }else{ alert('more than 4 years'); } } 

use moment.js, for an example: 例如,使用moment.js:

var years = moment().diff('1981-01-01', 'years',false);
if (years < 4) {
  alert('under 4 years');
}else{
  alert('more than 4 years');
}

Well there are many ways using through plain JS Date() and using moment.js Better is to use moment.js and use it as below - 好吧,有很多方法可以通过普通的JS Date()和moment.js使用,更好的方法是使用moment.js并按以下方式使用它-

 var firstDate = moment("2016-12-02", 'YYYY-MM-DD'); var secondDate = moment("2016-12-02", 'YYYY-MM-DD'); var duration = moment.duration(secondDate.diff(firstDate)); var years = duration.asYears(); if (years < 4) { alert('under 4 years'); }else{ alert('more than 4 years'); } 

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

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