Antoshjke
Antoshjke

Reputation: 462

DateTime.TryParseExact C# valid format and parsing

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?

Upvotes: 7

Views: 1758

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98740

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.

Upvotes: 9

Gustav
Gustav

Reputation: 55806

Further, your parsing of the time returns today's date at Midnight added the TimeSpan from parsing timeString.

Thus, to cut off today's date, do something like this:

// snip ..
DateTime datetimeOn = dateOn.Add(timeOn.TimeOfDay);
return SaveWorkshop(id, name, datetimeOn, capacity, description, duration, isCancelled);

or, of course, modify SaveWorkshop to create datetimeOn internally.

Edit

Also, you could parse in one go:

DateTime datetimeOn;
DateTime.TryParseExact(dateString + timeString, "MM/dd/yyyyh:mm tt", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out datetimeOn);

Upvotes: 0

jmcilhinney
jmcilhinney

Reputation: 54417

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

Upvotes: 2

Related Questions