C#中比较常用的DateTime结构的使用方法

2019-12-26 14:16:56王旭
  •       {          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方法
     

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

    文章中介绍了几个算是比较常用的方法,希望对大家的学习有所帮助,平时多阅读相关文章,积累经验。



    注:相关教程知识阅读请移步到c#教程频道。