如果日期时间是另一个日期时间的24小时,则返回

时间:2018-04-24 03:07:10

标签: c# datetime

我正在尝试将DateTime变量与另一个if (todaysDate == OtherDate) { //do stuff only if otherDate is within 24 hours of todaysDate } 变量进行比较,如果它们彼此相隔24小时,那么就做一些事情。例如,

class ExternalLink extends React.Component {

  constructor(props) {
    super(props)
    this.state = { showModal: false }
  }

  renderModal() {
    console.log("the link " + this.props.url + " was clicked.")

    return (
      <div className="modal show">
        <div className="modal-dialog modal-dialog-centered" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title" id="exampleModalLongTitle">Modal 
              title</h5>

              <button type="button" className="close" data-dismiss="modal" 
              aria-label="Close">
              <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div className="modal-body">
              ...
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" data- 
               dismiss="modal">Close</button>
              <button type="button" className="btn btn-primary">Save 
              changes</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  render() {
    return (
      <div>
        <a onClick={() => this.setState({showModal: true})}>{this.props.url}</a>
        {this.state.showModal && this.renderModal()}
      </div>
    );
  }
}

我知道我可以使用此处的运算符https://msdn.microsoft.com/en-us/library/ff986512(v=vs.110).aspx来比较日期,但这些比较似乎都没有给我我想要的东西,所以很奇怪如何实现这一点。

1 个答案:

答案 0 :(得分:6)

使用Subtract方法和TotalHours属性。

System.DateTime date1 = new System.DateTime(2018, 4, 24, 22, 15, 0);
System.DateTime date2 = new System.DateTime(2018, 4, 24, 13, 2, 0);

System.TimeSpan diff1 = date2.Subtract(date1);

Console.WriteLine(diff1.TotalHours);

if(diff1.TotalHours >= -24 && diff1.TotalHours <=24)
{
    Console.WriteLine("Within +/- 24 Hours");
}