获得两个日期之间的最小值(或最大值)的最快和最简单的方法是什么?有数学等价物吗?Min (& Math.Max)的日期?

我想做的事情是:

 if (Math.Min(Date1, Date2) < MINIMUM_ALLOWED_DATE) {
      //not allowed to do this
 }

显然上面的数学。Min没用,因为它们是日期。


当前回答

// Two different dates
var date1 = new Date(2013, 05, 13); 
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate); 

http://jsfiddle.net/5CR37/

其他回答

// Two different dates
var date1 = new Date(2013, 05, 13); 
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate); 

http://jsfiddle.net/5CR37/

没有内置的方法来做这个。你可以使用这样的表达:

(date1 > date2 ? date1 : date2)

求两者的最大值。

您可以编写一个泛型方法来计算任何类型的Min或Max(前提是Comparer<T>。默认设置是适当的):

public static T Max<T>(T first, T second) {
    if (Comparer<T>.Default.Compare(first, second) > 0)
        return first;
    return second;
}

你也可以使用LINQ:

new[]{date1, date2, date3}.Max()

DateTime扩展方法怎么样?

public static DateTime MaxOf(this DateTime instance, DateTime dateTime)
{
    return instance > dateTime ? instance : dateTime;
}

用法:

var maxDate = date1.MaxOf(date2);

将这两个方法放在一个Utility类中,并使用它们来获取任意数量的DateTimes的最小/最大值:

public static DateTime Min(params DateTime[] dates)
{
    if (dates.Length == 1) return dates[0];

    long minTicks = dates[0].Ticks;

    for (int i = 1; i < dates.Length; i++)
    {
        minTicks = Math.Min(minTicks, dates[i].Ticks);
    }

    return new DateTime(minTicks);
}

public static DateTime Max(params DateTime[] dates)
{
    if (dates.Length == 1) return dates[0];

    long maxTicks = dates[0].Ticks;

    for (int i = 1; i < dates.Length; i++)
    {
        maxTicks = Math.Max(maxTicks, dates[i].Ticks);
    }

    return new DateTime(maxTicks);
}
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;
    }
}

这允许日期有不同的“种类”,并返回被传入的实例(不返回一个由tick或Milliseconds构造的新的DateTime)。

[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);
    }

请注意,该测试在格林威治以东将失败。