C# 如何找到最大日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1129172/
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
How to find Max Date
提问by
I work in C# using VisualStudio 2005 on Windows. I want to find the max date between two dates.
我在 Windows 上使用 VisualStudio 2005 在 C# 中工作。我想找到两个日期之间的最大日期。
Suppose:
认为:
From Date: 10-1-2009//Day-Month-YYYY
To Date : 1-3-2009
I want to write a method which returns that "To Date" is the larger of the two.
我想编写一个方法来返回“To Date”是两者中较大的一个。
回答by Aaron Powell
public static DateTime WhichIsBigger(DateTime first, DateTime second) {
if(first > second) return first;
else return second;
}
Or a real 1-liner:
或真正的 1-liner:
Func<DateTime, DateTime, DateTime> whichIsBigger = (f, s) => f > s ? f : s;
回答by AgileJon
Oh come on, this one is screaming to be a one-liner
哦,拜托,这人尖叫着要成为单线
public static DateTime Max(DateTime a, DateTime b) {
return a > b ? a : b;
}
回答by Adam Lassek
The DateTime class stores points in time numerically as a 64-bit integer value called a tick. A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.
DateTime 类以数字方式将时间点存储为称为刻度的 64 位整数值。一个刻度代表一百纳秒或百万分之一秒。一毫秒有 10,000 个滴答声。
Since DateTime
is simply a numeric value, you can easily compare them as you would any two numbers using the <
or >
operators.
由于DateTime
它只是一个数值,因此您可以像使用<
or>
运算符一样轻松地比较它们。
回答by Ben Creighton
Try this on for size, no point in writing a Max routine ever again - use generics!
试试这个大小,再写一个 Max 例程没有意义 - 使用泛型!
public T Max<T>(T value1, T value2) where T:IComparable
{
return value1.CompareTo(value2) > 0 ? value1 : value2;
}
回答by Tony Zhu
You can use Linq to Objects extension method Max
like :
您可以使用 Linq to Objects 扩展方法,Max
例如:
new [] {date1,date2,date3}.Max();