我想比较两个dateTime。
例如:
date1 = 13/01/2004 12:20:00
date2 = 13/01/2004 12:35:00
result = Compare(date2-date1);
O/P : 15 Minutes
答案 0 :(得分:13)
要进行比较,您只需使用<
运算符:date1 < date2
。
如果您想与给定的分辨率进行比较,请尝试date1.TotalMinutes == date2.TotalMinutes
(在同一分钟进行比较)。
如果您想知道差异是否在特定时间范围内,请使用:
System.TimeSpan dt = date2.Subtract(date1);
if (dt.TotalMinutes < 15) //...
答案 1 :(得分:11)
试试这个:
TimeSpan diff = date2.Subtract(date1);
答案 2 :(得分:4)
怎么样
if (date1 < date2)
{
// date1 is before date2
}
答案 3 :(得分:3)
您可以使用
double minutes = d2.Subtract(d1).TotalMinutes;
以分钟为单位获得总差异。
答案 4 :(得分:1)
我不完全明白你在问什么。
如果你想在C#中表达你的伪代码,那就去吧......
//date1 = 13/01/2004 12:20:00
DateTime dateTime1 = new DateTime(2004, 01, 13, 12, 20, 0);
//date2 = 13/01/2004 12:35:00
DateTime dateTime2 = new DateTime(2004, 01, 13, 12, 35, 0);
//get the time difference - result = Compare(date2-date1);
TimeSpan result = dateTime2 - dateTime1;
//output is 15
Console.WriteLine(result.TotalMinutes);
答案 5 :(得分:1)
怎么样:
Timespan ts = date2 - date1;
Console.WriteLine("Value of Minutes = ", ts.Minutes);
答案 6 :(得分:0)
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now;
var x = date1.CompareTo(date2);
编辑:我现在看到你想要获得两个日期之间的时差。为此,您使用TimeSpan类。
答案 7 :(得分:0)
现在这是最好的选择。
using System;
public class Example
{
public static void Main()
{
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
答案 8 :(得分:0)
用Larry Wall的话说,有不止一种方法可以做到这一点。如果您要查找特定时间间隔内比较的-1,0,+ 1结果,请尝试以下变体之一;
internal static int XDateCompare(DateTime date, DateTime other, int ticks)
{
var diff = date.Ticks - other.Ticks;
var result = Math.Abs(diff) <= ticks ? 0
: diff <= 0 ? -1
: 1;
Console.WriteLine("{0}\t{1}\t{2}\ts={3} milSec={4}", diff, other, result, ticks, date.Subtract(other).Duration().TotalMilliseconds);
return result;
}
internal static int XDateCompare(DateTime date, DateTime other, double milliseconds)
{
double diff =
date.Subtract(other)
.TotalMilliseconds;
var result = Math.Abs(diff) <= milliseconds ? 0
: diff <= 0 ? -1
: 1;
Console.WriteLine("result {0} diff {1} vs ms {2}", result, diff, milliseconds);
return result;
}