6

Hello I have an unusual date format that I would like to parse into 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 cant seem to get started on this.

Thanks for any help.

1
  • Is the date allways having the same number of characters, i mean, the month and day are allways 2 digit long? Commented Nov 21, 2010 at 16:30

3 Answers 3

9
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: Wrapped the time separator token in single quotes as per Frédéric's comment

Sign up to request clarification or add additional context in comments.

1 Comment

beware of the : character in date/time format strings: it's the time separator token and it can surprise you, e.g. by resolving to the . character in Italian locales. You might want to wrap it inside single quotes to escape it and avoid trouble later on :)
5

You can use the DateTime.TryParseExact() static 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);

Comments

3

DateTime.TryParseExact()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.