Equivalent of Math.Min & Math.Max for Dates?

后端 未结 9 1929
渐次进展
渐次进展 2020-12-13 05:16

What\'s the quickest and easiest way to get the Min (or Max) value between two dates? Is there an equivalent to Math.Min (& Math.Max) for dates?

I want to do som

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 05:43

    public static class DateTool
    {
        public static DateTime Min(DateTime x, DateTime y)
        {
            return (x.ToUniversalTime() < y.ToUniversalTime()) ? x : y;
        }
        public static DateTime Max(DateTime x, DateTime y)
        {
            return (x.ToUniversalTime() > y.ToUniversalTime()) ? x : y;
        }
    }
    

    This allows the dates to have different 'kinds' and returns the instance that was passed in (not returning a new DateTime constructed from Ticks or Milliseconds).

    [TestMethod()]
        public void MinTest2()
        {
            DateTime x = new DateTime(2001, 1, 1, 1, 1, 2, DateTimeKind.Utc);
            DateTime y = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local);
    
            //Presumes Local TimeZone adjustment to UTC > 0
            DateTime actual = DateTool.Min(x, y);
            Assert.AreEqual(x, actual);
        }
    

    Note that this test would fail East of Greenwich...

提交回复
热议问题