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.
The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.
Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.
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
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);
DateTime.TryParseExact()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With