Common methods of C # DateTime structure

Source: Internet
Author: User
Tags date1

In project development, the date processing is often encountered. For example, in a query, you may often encounter queries by time period, sometimes by default, one months of data is taken out. When we submit data, we will need to record the current date, and so on. Here's a look at some common methods.

First, DateTime is a struct. Many times, it is considered a class. But it's not really, the description on MSDN is as follows:

DateTime structure: Represents 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>

MSDN Connection: MSDN DateTime structure

First, DateTime.Now properties

Instantiates a DateTime object that can be given a DateTime object as a date. The DateTime.Now property can then get the current time. If you want to count the data by year, month, and day, you can also use DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day to get it. In the same way, the current time division seconds can also be obtained in this manner. You can also add an operation at the current time, such as a time period.

        Static voidMain (string[] args) {DateTime Newchina=NewDateTime (1949,Ten,1);            Console.WriteLine (Newchina); Console.WriteLine ("Current Time:"); Console.WriteLine ("{ 0} years, {1} months, {2} days", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); Console.WriteLine ("{ 0}, {1} minutes, {2} seconds", DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); Console.WriteLine ("after three days: {0}", DateTime.Now.AddDays (3));        Console.ReadLine (); }

Results:

Two, ToString Method

The ToString method of DateTime has four overloaded methods. One of the overloads allows the string to be passed in, which means that you can convert the current DateTime object to an equivalent string form. For example, we will output the current time, date in YYYY-MM-DD format, time by 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 a IFormatProvider that converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information.

  Static voidMain (string[] args) {CultureInfo JAJP=NewCultureInfo ("JA-JP"); JaJP.DateTimeFormat.Calendar=NewJapanesecalendar (); DateTime Date1=NewDateTime (1867,1,1); DateTime Date2=NewDateTime (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.MinSupportedDa            Tetime, JaJP.DateTimeFormat.Calendar.MaxSupportedDateTime);        } console.readline (); }

Results:

Not too clear, Japanese history is so short? Baidu September 8, 1868, after the Meiji Restoration.

Pay the DateTimeFormatInfo class, here are the strings that correspond to the full time date format.

Three, DaysInMonth method and Isleapyear method

The DaysInMonth method requires two Int32 parameters that return the number of days in the specified month for a specified year. With regard to the number of days in the month, most only February need special care. The remaining months, regardless of the number of days in which the year is fixed. And February, not only 30 days or 31 days of the other months, she also divided a leap year non-leap years.

    Static void Main (string[] args)        {            Console.WriteLine ("days from 2000 to 2015 February " );              for (int.; i++)            {                Console.WriteLine ("{0} year February has: {1} days "2));            }            Console.ReadLine ();        }

Output Result:

As you can see from the output, February is a leap year for 29 days. But in fact, DateTime also provides a method for judging leap years isleapyear, the method as long as a Int32 parameter, if the input year is a leap month returns true, otherwise returns false. (The. Net framework is so intimate that everything you need is encapsulated and used directly.) If this is not the way to go, you have to follow the rules of the leap year to write a small method to judge.

 Static voidMain (string[] args) {Console.WriteLine ("2000 to 2015 mid-February days");  for(inti = -; I < -; i++)            {                if(Datetime.isleapyear (i)) Console.WriteLine ("{0} years is a leap year with {1} days in February", I, Datetime.daysinmonth (i,2)); ElseConsole.WriteLine ("{0} Year is common year, February has {1} days", I,datetime.daysinmonth (i,2));        } console.readline (); }

Microsoft is now going to. NETFramework open source, which means you can view the source code yourself. Attach the source code of the DateTime.cs, as well as the Isleapyear method. Although only two or three lines of code, but in the actual development, you may not think of a leap year in the calculation of the formula, or do not control. A well-packaged method saves you a lot of time.

Isleapyear method in DateTime.cs source code

      //Checks Whether a given year was a leap year. This method returns True if//Year was a leap year, or false if not. //         Public Static BOOLIsleapyear (intYear ) {            if(Year <1|| Year >9999) {                Throw NewArgumentOutOfRangeException (" Year", Environment.getresourcestring ("Argumentoutofrange_year"));            } contract.endcontractblock (); returnYear%4==0&& (Year% -!=0|| Year% -==0); }

Summarize

This paper introduces several methods which are more commonly used. Take a look at the date operation in your project. NETFramework provides us with a way to do this. A lot of times with the methods provided, you can easily get to the date or time we want.

Common methods of C # DateTime structure

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.