一. DateTime
在C#中,系統提供了許多關於時間處理的函數,我們可以通過System.DateTime.Now獲取系統時間.當然也可以用DateTime類來創建時間對象.下面給了幾個例子獲取系統時間的方法.
DateTime dt1 = new DateTime(2004, 10, 19);
Console.WriteLine("dt1: {0}", dt1);
DateTime dt2 = new DateTime(2004, 10, 19, 22, 47, 35);
Console.WriteLine("dt2: {0}", dt2);
DateTime dt3 = new DateTime(2004, 10, 19, 22, 47, 35, 259);
Console.WriteLine("dt3: {0}", dt3);
Stringtime1= System.DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss");
Console.WriteLine(time1);
程序運行的結果截圖是
System.DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")的意思是獲取系統當前時間,並以年-月-日-時-分-秒的格式顯示出來.
再看下一個有管時間的類:Timespan,就字面的意思應該知道它的中文意思時間間隔.先看一個例子:
TimeSpan oneweek = new TimeSpan(4, 12, 0, 0) +
new TimeSpan(2, 12, 0, 0);
//(4, 12, 0, 0)中的參數分別表示
days,hours,minutes,seconds.
DateTime now = DateTime.Now;
DateTime past = now - oneweek;
Console.WriteLine(oneweek.ToString());
Console.WriteLine(now.ToString());
Console.WriteLine(past.ToString());
輸出結果時
.在當前的時間上加上X秒./分/時/天等操作.
DateTime time1 = DateTime.Now;
DateTime time2 = DateTime.Now.AddYears(10);
DateTime time3 = DateTime.Now.AddMonths(11);
DateTime time4 = DateTime.Now.AddDays(7);
DateTime time5 = DateTime.Now.AddHours(12);
Console.WriteLine(time1.ToString());
Console.WriteLine(time2.ToString());
Console.WriteLine(time3.ToString());
Console.WriteLine(time4.ToString());
Console.WriteLine(time5.ToString());
程序運行的結果截圖是:
DateTime time2 = DateTime.Now.AddYears(10)的意思是把當前時間上加上10年後再賦值給 time2;
有關本地時間和標准UTC