Ash*_*shu 120 .net c# datetime
我不希望用户给出返回日期或时间.
如何比较输入的日期和时间是否低于当前时间?
如果当前日期和时间是2010年6月17日,下午12:25,我希望用户不能在2010年6月17日之前和下午12:25之前给出日期.
如果用户输入的时间是2010年6月16日和下午12:24,我的函数返回false
MuS*_*aNG 282
微软还实现了运营商的''和'>'.所以你用这些来比较两个日期.
if (date1 < DateTime.Now)
Console.WriteLine("Less than the current time!");
Run Code Online (Sandbox Code Playgroud)
Ahm*_*ıcı 162
MSDN:DateTime.Compare
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
// The example displays the following output:
// 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
Run Code Online (Sandbox Code Playgroud)
Sна*_*ƒаӽ 20
MuSTaNG的答案说明了一切,但我仍然在添加它以使其更精细,链接和所有.
传统的运营商
DateTime
自.NET Framework 1.1起可用.而且,加法和减法DateTime
的对象也是可能的使用常规的运营商+
和-
.
MSDN的一个例子:
平等:System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);
// areEqual gets false.
bool areEqual = april19 == otherDate;
otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;
Run Code Online (Sandbox Code Playgroud)
其他操作员也可以使用.
小智 10
如果您有两个看起来相同的 DateTime,但比较或等于没有返回您期望的结果,则可以按以下方法比较它们。
这是一个精度为 1 毫秒的示例:
bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);
Run Code Online (Sandbox Code Playgroud)
在一般情况下,您需要DateTimes
与相同的进行比较Kind
:
if (date1.ToUniversalTime() < date2.ToUniversalTime())
Console.WriteLine("date1 is earlier than date2");
Run Code Online (Sandbox Code Playgroud)
从解释MSDN约DateTime.Compare
(这也是相关的运营商一样>
,<
,==
等):
为了确定 t1 到 t2 的关系,Compare 方法比较了 t1 和 t2 的 Ticks 属性,但忽略了它们的 Kind 属性。在比较 DateTime 对象之前,请确保这些对象表示同一时区的时间。
因此,在处理以DateTimes
不同时区表示的内容时,简单的比较可能会产生意想不到的结果。
归档时间: |
|
查看次数: |
204944 次 |
最近记录: |