Vy Do
Vy Do

Reputation: 52636

How to convert a specific string to DateTime?

I have a string in this format:

Tuesday, Sep 01, 2020 04:15
Thursday, Aug 27, 2020 03:56
Friday, Aug 28, 2020 07:30
Tuesday, Aug 04, 2020 08:00
[Route("/test")]
public async void TestParseTime()
{
    string pattern = "dddd, MMM dd, YYYY HH:MM";
    string newsTimeString = "Thursday, Aug 27, 2020 03:56";
    DateTime newsTime = DateTime.ParseExact(newsTimeString, pattern, null);
    Console.WriteLine("newsTime = " + newsTime);
}

But the parsing of the string to datetime fails with the following exception:

enter image description here

How to convert it to a DateTime in C#?

Upvotes: 1

Views: 106

Answers (2)

Mong Zhu
Mong Zhu

Reputation: 23732

I would suggest to use the powerfull Convert.ToDateTime method and simply feed the input in there:

string newsTimeString = "Thursday, Aug 27, 2020 03:56";
DateTime newsTime = Convert.ToDateTime(newsTimeString);
Console.WriteLine("newsTime = " + newsTime);

Output:

newsTime = 27.08.2020 03:56:00

Actually the "Thursday" string is superfluous information for the DateTime object. Because it will know the day of week from the calendar. You can print it via the property:

Console.WriteLine("Day = " + newsTime.DayOfWeek);

Output:

Day = Thursday

EDIT:

Apparently: "Convert.ToDateTime is just a call to DateTime.Parse" (comment by Panagiotis Kanavos) So in this case you can also use:

DateTime newsTime = DateTime.Parse(newsTimeString);

and get the same result, without specifying any format.

Disclaimer:

From the Remarks section of the documentation:

"If value is not null, the return value is the result of invoking the
DateTime.Parse method on value using the formatting information in a
DateTimeFormatInfo object that is initialized for the current culture." -

Upvotes: 4

Prince Tegaton
Prince Tegaton

Reputation: 322

Your pattern is incorrect. patterns are case-sensitive. Use this pattern instead:

dddd, MMM dd, yyyy hh:mm

string pattern = "dddd, MMM dd, yyyy hh:mm";
Console.WriteLine(DateTime.Now.ToString(pattern));

string newsTimeString = "Thursday, Aug 27, 2020 03:56";
DateTime newsTime = DateTime.ParseExact(newsTimeString, pattern, null);
Console.WriteLine("newsTime = " + newsTime);

Upvotes: 0

Related Questions