我想使用 moment.js 检查当前日期在从07-11-2017到05-01-2018之间的日期之间是否有效。< / p>
任何帮助?? 怎么做?
我有以下代码:
import React, {Component} from 'react';
import moment from 'moment';
class Dates extends Component {
constructor() {
super();
this.state = {
dateNow: moment(),
availability:''
}
}
componentDidMount() {
let startdate = moment("17-11-2017");
let enddate = moment("05-01-2018");
this.setState({
availability: 'Yes'
});
}
render() {
return(
<div>
<div>{this.state.dateNow}</div>
<table>
<tr>
<td>Available from 7th November,2017 to 5th January,2018?</td>
<td>{this.state.availability}</td>
</tr>
</table>
</div>
);
}
}
export default Dates;
答案 0 :(得分:5)
使用isBetween
检查可用性,如
moment('22-11-2017').isBetween('17-11-2017', '05-01-2018');
如果条件为真,则方法返回true
,否则为false
。
答案 1 :(得分:2)
首先将其转换为有效的日期对象
let date = moment("22-11-2017", "DD-MM-YYYY")
let startdate = moment("17-11-2017","DD-MM-YYYY");
let enddate = moment("05-01-2018","DD-MM-YYYY");
然后转换日期格式的日期 使用
var a = date.toDate();b= startdate.toDate(),c=enddate.toDate();
然后使用简单的if条件
if (a.getTime() >=b.getTime() && a.getTime() <=c.getTime())
console.log('do your stuff')
else
console.log('sorry timeout')
您也可以使用此
date.isBetween(startdate,enddate)