幾點重要的用法:
a 先來介紹幾個方法
TimeSpan.Minutes(其他時間比如天數,小時數,秒數都一樣的情況下得到的分鐘數的差),其他的Hours,Second一樣
DateTime.Tick :是一個計時周期,表示一百納秒,即一千萬分之一秒,那么 Ticks 在這里表示總共相差多少個時間周期,即:9 * 24 * 3600 * 10000000 + 23 * 3600 * 10000000 + 59 * 60 * 10000000 + 59 * 10000000 = 8639990000000。3600 是一小時 的秒數
TimeSpan.TotalDays:兩個時間段相差的日數,其他的TotalHours,TotalMinutes,TotalSeconds 一樣
b 兩個時間的差
舉例說明
時間 1 是 2010-1-2 8:43:35;
時間 2 是 2010-1-12 8:43:34。
用時間 2 減時間 1,得到一個 TimeSpan 實例。
那么時間 2 比時間 1 多 9 天 23 小時 59 分 59 秒。
那么,Days 就是 9,Hours 就是 23,Minutes 就是 59,Seconds 就是 59。
所以以后想知道兩個時間段的差就容易的多了
TimeSpan Format Helper
class TimeSpanUtility
{
public static string FormatString(TimeSpan aTimeSpan)
{
string newFormat = aTimeSpan.ToString("d'd 'h'h 'm'm 's's'");
// 1d 3h 43m 23s
return newFormat;
}
public static string TimeSpanInWords(TimeSpan aTimeSpan)
{
List<string> timeStrings = new List<string>();
int[] timeParts = new[] { aTimeSpan.Days, aTimeSpan.Hours, aTimeSpan.Minutes, aTimeSpan.Seconds };
string[] timeUnits = new[] { "day", "hour", "minute", "second" };
for (int i = 0; i < timeParts.Length; i++)
{
if (timeParts[i] > 0)
{
timeStrings.Add(string.Format("{0} {1}", timeParts[i], Pluralize(timeParts[i], timeUnits[i])));
}
}
return timeStrings.Count != 0 ? string.Join(", ", timeStrings.ToArray()) : "0 seconds";
}
private static string Pluralize(int n, string unit)
{
if (string.IsNullOrEmpty(unit)) return string.Empty;
n = Math.Abs(n); // -1 should be singular, too
return unit + (n == 1 ? string.Empty : "s");
}
}
public class Client
{
static void Main()
{
// 12 days, 23 hours, 24 minutes, 2 seconds.
TimeSpan span = new TimeSpan(12, 23, 24, 2);
Console.WriteLine(TimeSpanUtility.TimeSpanInWords(span)); // Output: 12 days, 23 hours, 24 minutes, 2 seconds
Console.WriteLine(TimeSpanUtility.FormatString(span)); // Output: 12d 23h 24m 2s
}
}
新聞熱點
疑難解答