How to parse an unusual date string

Hello, I have an unusual date format that I would like to parse in a DateTime object

string date ="20101121"; // 2010-11-21 string time ="13:11:41: //HH:mm:ss 

I would like to use DateTime.Tryparse() , but I cannot start with this.

Thanks for any help.

+6
c #
source share
3 answers
 string date ="20101121"; // 2010-11-21 string time ="13:11:41"; //HH:mm:ss DateTime value; if (DateTime.TryParseExact( date + time, "yyyyMMddHH':'mm':'ss", new CultureInfo("en-US"), System.Globalization.DateTimeStyles.None, out value)) { Console.Write(value.ToString()); } else { Console.Write("Date parse failed!"); } 

Edit: The single-quote time separator marker is completed according to Frederick's remark

+9
source share

You can use the static DateTime.TryParseExact () method with a custom format :

 using System.Globalization; string date = "20101121"; // 2010-11-21 string time = "13:11:41"; // HH:mm:ss DateTime convertedDateTime; bool conversionSucceeded = DateTime.TryParseExact(date + time, "yyyyMMddHH':'mm':'ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out convertedDateTime); 
+5
source share

DateTime.TryParseExact ()

+3
source share

All Articles