C# 日期相减

有两种方法:直接调用 DateTime.Subtract,得到一个TimeSpan
或者直接DateTime.Tricks相减,差值生成一个TimeSpan,如果想直接得到相差的秒数,可以把差值除以1000000

 

private static void SubDateTime() { DateTime dt1 = Convert.ToDateTime("2010-01-11"); DateTime now = DateTime.Now; TimeSpan t = now.Subtract(dt1); Console.Write(" days/hour/minute/second: " + t.Days + "/" + t.Hours + "/" + t.Minutes + "/" + t.Seconds); long diff = dt1.Ticks - now.Ticks; t = new TimeSpan(diff); Console.Write(" days/hour/minute/second: " + t.Days + "/" + t.Hours + "/" + t.Minutes + "/" + t.Seconds); long diff2 = ((t.Days * 24 + t.Hours) * 60 + t.Minutes) * 60 + t.Seconds; Console.Write(" t/diff/diff2: " + t + "/" + diff + "/" + diff2); } 

 

 

结果

 days/hour/minute/second: 0/13/24/31
 days/hour/minute/second: 0/-13/-24/-31
 t/diff/diff2: -13:24:31.9482950/-482719482950/-48271

 

你可能感兴趣的:(C# 日期相减)