Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse an unusual date string

Tags:

c#

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.

like image 641
Brad Avatar asked Nov 21 '10 16:11

Brad


People also ask

How do you parse a Date?

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.

How do you parse a Date in python?

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.


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

like image 182
cspolton Avatar answered Oct 20 '22 03:10

cspolton


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);
like image 30
Frédéric Hamidi Avatar answered Oct 20 '22 04:10

Frédéric Hamidi


DateTime.TryParseExact()

like image 24
Ilia G Avatar answered Oct 20 '22 02:10

Ilia G