Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParseExact C# valid format and parsing

Tags:

c#

datetime

Came across with a problem of pasing format.

if (!DateTime.TryParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateOn))
{
     return false;
}
else if (!DateTime.TryParseExact(timeString, "hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out timeOn))
{
     return false;
}

return SaveWorkshop(id, name, dateOn, timeOn, capacity, description, duration, isCancelled);

Using Bootstrap Datetimepicker, it does takes a strings from textboxes in format

dateString = 11/28/2015 and timeString = 6:46 AM

But in the result I do have false and is parsing default date. What could be the problem?

like image 288
Antoshjke Avatar asked Nov 25 '15 11:11

Antoshjke


2 Answers

For your timeString, you need to use h instead of hh specifier.

hh specifier is needs a leading zero for single digits like 06. You need to use h specifier instead.

That's why your second DateTime.TryParseExact returns false and timeOn will be it's default value.

like image 79
Soner Gönül Avatar answered Sep 28 '22 11:09

Soner Gönül


If I'm not mistaken, "hh" requires a two-digit hour, which you don't have. Use "h" for non-zero-padded values.

like image 26
jmcilhinney Avatar answered Sep 28 '22 10:09

jmcilhinney