Valid DateTime.TryParseExact C # format and parsing

Interacted with a pasing format problem.

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 takes strings from text fields in the format

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

But as a result, I have a lie and default date parsing. What could be the problem?

+7
c # datetime
source share
3 answers

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

hh specifier requires leading zero for single digits such as 06 . Instead, you need to use the h specifier .

This is why your second DateTime.TryParseExact returns false and timeOn will be its default value.

+9
source share

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

+2
source share

Next, your time parsing returns today the date in Midnight by adding the TimeSpan from the timeString parsing.

So, to disable 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

In addition, you can parse at a time:

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

All Articles