[C#] 計算兩個日期間差異
在C#中計算兩個日期(DateTime)的結果會輸出(TimeSpan)DateTime now = DateTime.Now;DateTime after = DateTime.Now.AddDays(-7);
TimeSpan tsDiff = now - after; // 也可用 now.Subtract(after)
Console.WriteLine(ts);上面計算的結果可以用天、時、分、秒、毫秒為單位顯示,輸出類型為double
[*]輸出差異總天數
double diffTotalDay = tsDiff.TotalDays;
[*]輸出差異總小時數
double diffTotalHour = tsDiff.TotalHours;
[*]輸出差異總分鐘數
double diffTotalMinute = tsDiff.TotalMinutes;
[*]輸出差異總秒數
double diffTotalSecond = tsDiff.TotalSeconds;
[*]輸出差異總毫秒數
double diffTotalMillisecond = tsDiff.TotalMilliseconds;
如果是個別顯示天、時、分、秒、毫秒的數量,就要用到TimeSpan的屬性,類型為intint diffDay = tsDiff.Days;
int diffHour = tsDiff.Hours;
int diffMinute = tsDiff.Minutes;
int diffSecond = tsDiff.Seconds;
int diffMillisecond = tsDiff.Milliseconds;
頁:
[1]