Home>

In project development,Often encountered date processing.For example, in a query,You may often encounter queries by time period,Sometimes one month of data is taken out by default.When we submit data,Will need to record the current date,and many more. Let ’s take a look at somecommonly used ways.

First, datetime is a struct. most of the time,Think of it as a class.But it really isn't,The description on msdn is as follows:

datetime structure:means a moment in time,Usually expressed as a date and time of day.grammar:

[serializableattribute]
public struct datetime:icomparable, iformattable,  iconvertible, iserializable, icomparable<datetime> ;, iequatable<datetime>

First, the datetime.now property

Instantiate a datetime object, you can get a datetime object with the specified number as the year, month and day. The datetime.now property gets the current time.If i want to separate statistics by year, month, and day,Also available as datetime.now.year, datetime.now.month, datetime.now.day. Similarly, the current hour, minute, and second can also be obtained in this way.You can also add a period of time to the current time.

static void main (string [] args)
    {
      datetime newchina=new datetime (1949, 10, 1);
      console.writeline (newchina);
      console.writeline ("Current time:");
      console.writeline ("{0} year, {1} month, {2} day", datetime.now.year, datetime.now.month, datetime.now.day);
      console.writeline ("{0} hours, {1} minutes, {2} seconds", datetime.now.hour, datetime.now.minute, datetime.now.second);
      console.writeline ("Three days later:{0}", datetime.now.adddays (3));
      console.readline ();
    }

result:

Second, the tostring method

There are four overloads of datetime's tostring method.One of the overloaded methods allows you to pass in a string, which means that you can convert the current datetime object into an equivalent string form.For example, we output the current time,The date is in yyyy-mm-dd format, and the time is in hh:mm:ss format.

console.writeline (datetime.now.tostring ("yyyy-mm-dd"));
  console.writeline (datetime.now.tostring ("hh:mm:ss"));

Another overloaded form is the need to provide ifformatprovider, which uses the specified culture-specific format information to convert the value of the current datetime object to its equivalent string representation.

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 ();
    }

result:

Third, the daysinmonth method and isleapyear method

The daysinmonth method takes two int32 parameters and returns the number of days in the specified month for the specified year.Regarding the number of days in the month,Most require special care only in February.The remaining months,The number of days in each year is fixed.And in February,Not only is it not 30 or 31 days in other months, she has a leap year and a non-leap year.

static void main (string [] args)
    {
      console.writeline ("Number of days in February-March 2015");
      for (int i=2000;i<2015;i ++)
      {
        console.writeline ("In February {0}:{1} days", i, datetime.daysinmonth (i, 2));
      }
      console.readline ();
    }

Output results:

As can be seen from the output,The year of 29 days in February is a leap year.In fact, datetime also provides a method isleapyear to determine the leap year. This method only requires an int32 parameter. If the year entered is a leap year, it returns true, otherwise it returns false. (The .net framework is so intimate,Everything i want is packaged for you,Use it directly.If not,You have to write a small method to judge yourself according to the rules of leap years.

static void main (string [] args)
    {
      console.writeline ("Number of days in February-March 2015");
      for (int i=2000;i<2015;i ++)
      {
        if (datetime.isleapyear (i))
          console.writeline ("The year {0} is a leap year,February has {1} days ", i, datetime.daysinmonth (i, 2));
        else
          console.writeline ("The year {0} is an average year,February has {1} days ", i, datetime.daysinmonth (i, 2));
      }
      console.readline ();
    }

Microsoft has now.netframework is open source, which means you can check the source code yourself.Attach the source code link of datetime.cs,And the source code for the isleapyear method.Although only two or three lines of code,But in actual development,You may not remember the formula for calculating leap years,Or not sure.Encapsulated methods save you a lot of time.

isleapyear method in datetime.cs source code

  //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);
    }
c
  • Previous Analysis of NET logical layered architecture
  • Next JavaScript to write, read, and delete cookies