The string representation of the C # Date and time is converted to its datetime equivalent (stringtodatetime)

Source: Internet
Author: User

I. Standard date and time string conversions

Converting the string representation of a date and time to its equivalent DateTime object is a very common type conversion in development, and the way we use it most often is:

// if S is null, throws a ArgumentNullException exception // If s does not contain a valid string representation of the date and time, throw FormatException DateTime datetime.parse (string  s); BOOL Datetime.tryparse (string out DateTime result);

DateTime.Parse may throw exceptions during processing to make code more complex, so we recommend the Datetime.tryparse method.

To avoid repeating coding and reducing the amount of code written at development time, we encapsulate the converted code in our own public help library:

        /// <summary>        ///Convert to date/// </summary>        /// <param name= "Data" >Data</param>         Public StaticDateTime ToDate (Objectdata) {            if(Data = =NULL)                returnDatetime.minvalue;            DateTime result; returnDatetime.tryparse (data. ToString (), outResult)?Result:DateTime.MinValue; }        /// <summary>        ///Convert to a nullable date/// </summary>        /// <param name= "Data" >Data</param>         Public StaticDatetime? Todateornull (Objectdata) {            if(Data = =NULL)                return NULL;            DateTime result; if(Datetime.tryparse (data. ToString (), outresult)) returnresult; return NULL; }

For added convenience, we can also do a method extension of the string type (Extension), which is no longer demonstrated here.

Two. custom format date and time string conversions

Sometimes there are special requirements that require converting a custom format date and time string to a DateTime object, which cannot be converted with the above method.

// the string that needs to be converted, that is, the month-day, and then the time string " 07-13 15:50:42 "

At this point we can use the following method:

// if DATETIMESTR or format is null, a ArgumentNullException exception is thrown // throws FormatException exception if DATETIMESTR or format is an empty string DateTime datetime.parseexact (stringstring  format, IFormatProvider provider);
BOOL DateTime.ParseExact (stringstring out DateTime result);

Examples of use are as follows:

var " 07-13 15:50:42 " ; var " MM-DD HH:mm:ss ", CultureInfo.InvariantCulture);

We also encapsulate it:

        /// <summary>        ///Convert to date, based on custom format string/// </summary>        /// <param name= "Data" ></param>        /// <param name= "format" ></param>        /// <param name= "provider" ></param>        /// <returns></returns>         Public StaticDateTime ToDate (ObjectDatastringFormat, IFormatProvider Provider =NULL)        {            if(Data = =NULL)                returnDatetime.minvalue;            DateTime result; returnDatetime.tryparseexact (data. ToString (), format, provider??CultureInfo.InvariantCulture, Datetimestyles.none, outresult)?Result:DateTime.MinValue; }        /// <summary>        ///Convert to a nullable date/// </summary>        /// <param name= "Data" >Data</param>         Public StaticDatetime? Todateornull (ObjectDatastringFormat, IFormatProvider Provider =NULL)        {            if(Data = =NULL)                return NULL;            DateTime result; if(Datetime.tryparseexact (data. ToString (), format, provider?? CultureInfo.InvariantCulture, Datetimestyles.none, outresult)) returnresult; return NULL; }

The string representation of a C # date and time is converted to its datetime equivalent (stringtodatetime)

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.