C# DateTime結構的經常使用方法

在項目開發中,常常會碰到日期處理。好比查詢中,可能會常常遇到按時間段查詢,有時會默認取出一個月的數據。當咱們提交數據時,會須要記錄當前日期,等等。下面就看看一些經常使用的方法。ide

首先,DateTime是一個struct。不少時候,會把它當成一個類。但它真的不是,MSDN上的描述以下:spa

DateTime結構:表示時間上的一刻,一般以日期和當天的時間表示。語法:code

[SerializableAttribute]
public struct DateTime : IComparable, IFormattable, 
    IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>

MSDN鏈接:MSDN DateTime結構orm

1、DateTime.Now屬性對象

實例化一個DateTime對象,能夠將指定的數字做爲年月日獲得一個DateTime對象。而DateTime.Now屬性則可得到當前時間。若是你想按年、月、日分別統計數據,也可用DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day獲取。同理,當前的時分秒也能夠這樣的方式獲取。還能夠在當前時間加上一個段時間等操做。blog

        static void Main(string[] args)
        {
            DateTime newChina = new DateTime(1949, 10, 1);
            Console.WriteLine(newChina);
            Console.WriteLine("當前時間:");
            Console.WriteLine("{0}年,{1}月,{2}日",DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            Console.WriteLine("{0}時,{1}分, {2}秒",DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            Console.WriteLine("三天後:{0}",DateTime.Now.AddDays(3));
            Console.ReadLine();
        }

結果:開發

2、ToString方法字符串

 DateTime的ToString方法有四種重載方式。其中一個重載方式容許傳入String,這就意味着你能夠將當前DateTime對象轉換成等效的字符串形式。好比咱們將當前時間輸出,日期按yyyy-mm-dd格式,時間按hh:mm:ss格式。get

   Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd"));
   Console.WriteLine(DateTime.Now.ToString("hh:mm:ss"));

還有一個重載形式是須要提供IFormatProvider,使用指定的區域性特定格式信息將當前 DateTime 對象的值轉換爲它的等效字符串表示形式。源碼

  static void Main(string[] args)
        {
            CultureInfo jaJP = new CultureInfo("ja-JP");
            jaJP.DateTimeFormat.Calendar = new JapaneseCalendar();
            DateTime date1 = new DateTime(1867, 1, 1);
            DateTime date2 = new DateTime(1967, 1, 1);
            
            try
            {
                Console.WriteLine(date2.ToString(jaJP));
                Console.WriteLine(date1.ToString(jaJP));
            }
            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("{0:d} is earlier than {1:d} or later than {2:d}",
                                  date1,
                                  jaJP.DateTimeFormat.Calendar.MinSupportedDateTime,
                                  jaJP.DateTimeFormat.Calendar.MaxSupportedDateTime);
            }
            Console.ReadLine();
        }

結果:

沒太明白,日本歷史那麼短?百度了一下1868年9月8日,明治維新之後了。

DateTimeFormatInfo類, 這裏有比較全的時間日期格式對應的字符串。

3、DaysInMonth方法及IsLeapYear方法

 DaysInMonth方法須要兩個Int32型參數,返回指定年份指定月份的天數。關於月份的天數,多數只有2月須要特殊照顧一下。剩餘的月份,不管哪一年的天數都是固定的。而二月呢,不但不是其餘月份的30天或31天,她還分個閏年非閏年。

    static void Main(string[] args)
        {
            Console.WriteLine("2000年至2015年中二月的天數");
            for (int i = 2000; i < 2015; i++)
            {
                Console.WriteLine("{0}年2月有:{1}天", i, DateTime.DaysInMonth(i, 2));
            }
            Console.ReadLine();
        }

輸出結果:

從輸出結果中能夠看出,2月爲29天的年份爲閏年。但其實DateTime還提供了判斷閏年的方法IsLeapYear,該方法只要一個Int32的參數,若輸入的年份是閏年返回true,不然返回false。(.Net Framework就是這麼貼心,你要的東西都給你封裝好了,直接拿來用好了。)要是沒這個方法呢,得本身去按照閏年的規則去寫個小方法來判斷。

 static void Main(string[] args)
        {
            Console.WriteLine("2000年至2015年中二月的天數");
            for (int i = 2000; i < 2015; i++)
            {
                if (DateTime.IsLeapYear(i))
                    Console.WriteLine("{0}年是閏年,2月有{1}天", i, DateTime.DaysInMonth(i, 2));
                else
                    Console.WriteLine("{0}年是平年,2月有{1}天",i,DateTime.DaysInMonth(i,2));
            }
            Console.ReadLine();
        }

微軟如今已經將.NetFramework開源了,這意味着能夠本身去查看源代碼了。附上DateTime.cs的源碼連接,以及IsLeapYear方法的源代碼。雖然僅僅兩三行代碼,但在實際開發中,你可能一時間想不起閏年的計算公式,或者拿捏不許。封裝好的方法爲你節省大量時間。

DateTime.cs源碼中IsLeapYear方法

      // Checks whether a given year is a leap year. This method returns true if
        // year is a leap year, or false if not.
        //
        public static bool IsLeapYear(int year) {
            if (year < 1 || year > 9999) {
                throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Year"));
            }
            Contract.EndContractBlock();
            return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
        }

 總結

介紹了幾個算是比較經常使用的方法。在本身的項目中遇到日期操做的時候,多看看.NetFramework給咱們提供了什麼樣的方法。不少時候用所提供的方法拼湊一下,就能輕易的獲取到咱們想要的日期或者時間。

相關文章
相關標籤/搜索