Reputation: 21160
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
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
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