converting strings into dates in C #

Source: Internet
Author: User

We are working with the string date format commonly used Datetime.pares () but this form of conversion is quite limited, and some C # is not going to understand the date format you write as 20031231. So how does a string like "20100101" or other forms be converted into a date type?

one, the form of stitching strings

II,convert.todatetime (String)

The string format is required and must be YYYY-MM-DD HH:MM:SS

Iii. Convert.todatetime (String, IFormatProvider)

DateTime DT;
DateTimeFormatInfo Dtformat = new System.globalizationdatetimeformatinfo ();
Dtformat.shortdatepattern = "YYYY/MM/DD";
DT = Convert.todatetime ("2011/05/26", Dtformat);

Iv.datetime.parseexact ()

String datestring = "20110526";
DateTime dt = DateTime.ParseExact (datestring, "YyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
Or
DateTime dt = DateTime.ParseExact (datestring, "YyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

V. Datetime.tryparse (String,out DateTime)

1, more often, will use the Datetime.tryparse (string,out datetime) method, because this method has security mechanism, when the string content is not correct, you can return the minimum value of the date MinValue. It is possible to determine the success of the conversion by returning the bool value. DateTime.ParseExact () needs to be converted in a specific format, with strict requirements for formatting, and an error if the string is not of the date content and the amount resembles "asdfasd".

2, after conversion with Datetime.tryparse (String,out datetime), the resulting datetime can be datetime. ToString ("ddd, MMM. DD ") to convert to a special demand format, more flexible and convenient.

converting strings into dates in C #

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.