.net 日期的 Math.Min 和 Math.Max 的等价物?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1985317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent of Math.Min & Math.Max for Dates?
提问by hawbsl
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?
获取两个日期之间的最小值(或最大值)的最快和最简单的方法是什么?是否有相当于 Math.Min (& Math.Max) 的日期?
I want to do something like:
我想做类似的事情:
if (Math.Min(Date1, Date2) < MINIMUM_ALLOWED_DATE) {
//not allowed to do this
}
Obviously the above Math.Min doesn't work because they're dates.
显然上面的 Math.Min 不起作用,因为它们是日期。
回答by Mehrdad Afshari
There's no built in method to do that. You can use the expression:
没有内置的方法可以做到这一点。您可以使用以下表达式:
(date1 > date2 ? date1 : date2)
to find the maximum of the two.
找出两者中的最大值。
You can write a generic method to calculate Minor Maxfor any type (provided that Comparer<T>.Defaultis set appropriately):
您可以编写通用方法来计算Min或Max用于任何类型(前提Comparer<T>.Default是设置适当):
public static T Max<T>(T first, T second) {
if (Comparer<T>.Default.Compare(first, second) > 0)
return first;
return second;
}
You can use LINQ too:
您也可以使用 LINQ:
new[]{date1, date2, date3}.Max()
回答by Guffa
There is no overload for DateTime values, but you can get the long value Ticksthat is what the values contain, compare them and then create a new DateTime value from the result:
DateTime 值没有重载,但您可以获得这些Ticks值所包含的长值,比较它们,然后从结果中创建一个新的 DateTime 值:
new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))
(Note that the DateTime structure also contains a Kindproperty, that is not retained in the new value. This is normally not a problem; if you compare DateTime values of different kinds the comparison doesn't make sense anyway.)
(请注意,DateTime 结构还包含一个Kind属性,该属性不会保留在新值中。这通常不是问题;如果您比较不同类型的 DateTime 值,则无论如何比较都没有意义。)
回答by Marc Gravell
How about:
怎么样:
public static T Min<T>(params T[] values)
{
if (values == null) throw new ArgumentNullException("values");
var comparer = Comparer<T>.Default;
switch(values.Length) {
case 0: throw new ArgumentException();
case 1: return values[0];
case 2: return comparer.Compare(values[0],values[1]) < 0
? values[0] : values[1];
default:
T best = values[0];
for (int i = 1; i < values.Length; i++)
{
if (comparer.Compare(values[i], best) < 0)
{
best = values[i];
}
}
return best;
}
}
// overload for the common "2" case...
public static T Min<T>(T x, T y)
{
return Comparer<T>.Default.Compare(x, y) < 0 ? x : y;
}
Works with any type that supports IComparable<T>or IComparable.
适用于任何支持IComparable<T>或 的类型IComparable。
Actually, with LINQ, another alternative is:
实际上,使用 LINQ,另一种选择是:
var min = new[] {x,y,z}.Min();
回答by user450
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).
这允许日期具有不同的“种类”并返回传入的实例(不返回从 Ticks 或 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);
}
Note that this test would fail East of Greenwich...
请注意,此测试将在格林威治以东失败......
回答by Toshi
Linq.Min()/ Linq.Max()approach:
Linq.Min()/Linq.Max()方法:
DateTime date1 = new DateTime(2000,1,1);
DateTime date2 = new DateTime(2001,1,1);
DateTime minresult = new[] { date1,date2 }.Min();
DateTime maxresult = new[] { date1,date2 }.Max();
回答by R. Salisbury
If you want to call it more like Math.Max, you can do something like this very short expression body:
如果你想称它为更像 Math.Max,你可以做一些像这个非常短的表达式体:
public static DateTime Max(params DateTime[] dates) => dates.Max();
[...]
var lastUpdatedTime = DateMath.Max(feedItemDateTime, assemblyUpdatedDateTime);
回答by Oundless
How about a DateTimeextension method?
怎么样DateTime扩展方法?
public static DateTime MaxOf(this DateTime instance, DateTime dateTime)
{
return instance > dateTime ? instance : dateTime;
}
Usage:
用法:
var maxDate = date1.MaxOf(date2);
回答by Craig Brunetti
Now that we have LINQ, you can create an array with your two values (DateTimes, TimeSpans, whatever) and then use the .Max() extension method.
现在我们有了 LINQ,您可以使用两个值(DateTimes、TimeSpans 等)创建一个数组,然后使用 .Max() 扩展方法。
var values = new[] { Date1, Date2 };
var max = values.Max();
It reads nice, it's as efficient as Max can be, and it's reusable for more than 2 values of comparison.
它读起来不错,它的效率与 Max 一样高,并且可重复用于 2 个以上的比较值。
The whole problem below worrying about .Kind is a big deal... but I avoid that by never working in local times, ever. If I have something important regarding times, I always work in UTC, even if it means more work to get there.
下面担心 .Kind 的整个问题是一个大问题......但我从不在本地时间工作,永远避免这种情况。如果我有一些重要的时间问题,我总是在 UTC 工作,即使这意味着需要更多的工作才能到达那里。
回答by Sergey Suvorov
// 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);

