Brad
Brad

Reputation: 21160

How do I parse an unusual date string

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.

Upvotes: 6

Views: 431

Answers (3)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

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);

Upvotes: 5

spolto
spolto

Reputation: 4551

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

Upvotes: 9

Ilia G
Ilia G

Reputation: 10211

DateTime.TryParseExact()

Upvotes: 3

Related Questions