How to check if one DateTime is greater than the other in C#

前端 未结 10 675
遇见更好的自我
遇见更好的自我 2021-02-03 16:28

I have two DateTime objects: StartDate and EndDate. I want to make sure StartDate is before EndDate. How is this

10条回答
  •  时光取名叫无心
    2021-02-03 17:20

    I had the same requirement, but when using the accepted answer, it did not fulfill all of my unit tests. The issue for me is when you have a new object, with Start and End dates and you have to set the Start date ( at this stage your End date has the minimum date value of 01/01/0001) - this solution did pass all my unit tests:

        public DateTime Start
        {
            get { return _start; }
            set
            {
                if (_end.Equals(DateTime.MinValue))
                {
                    _start = value;
                }
                else if (value.Date < _end.Date)
                {
                    _start = value;
                }
                else
                {
                    throw new ArgumentException("Start date must be before the End date.");
                }
            }
        }
    
    
        public DateTime End
        {
            get { return _end; }
            set
            {
                if (_start.Equals(DateTime.MinValue))
                {
                    _end = value;
                }
                else if (value.Date > _start.Date)
                {
                    _end = value;
                }
                else
                {
                    throw new ArgumentException("End date must be after the Start date.");
                }
            }
        }
    

    It does miss the edge case where both Start and End dates can be 01/01/0001 but I'm not concerned about that.

提交回复
热议问题