The following fails after executing the highlighted line.
String was not recognized as a valid DateTime.
It's happening all the sudden, worked when it was 12PM or so... ? Now its 4:54PM and no go. What the heck is going on?
You should be using hh:mm:ss tt
as the format string - HH
is for the 24-hour clock, at which point you're saying it's 4AM... but with PM as the AM/PM signifier.
Basically, use hh
with tt
, or HH
on its own.
Using Noda Time, you'd use:
private static readonly LocalTimePattern TimePattern =
LocalTimePattern.CreateWithInvariantCulture("hh:mm:ss tt");
// TODO: Check this is what you want! We can't tell from your example.
private static readonly LocalDatePattern DatePattern =
LocalDatePattern.CreateWithInvariantCulture("dd/MM/yyyy");
private static readonly LocalDateTimePattern DateTimePattern =
LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss");
public static string GetMergedDateTime(string dateText, string timeText)
{
// The Value property throws an exception if parsing failed. You can
// check that with the Success property first though.
LocalDate date = DatePattern.Parse(dateText).Value;
LocalTime time = TimePattern.Parse(timeText).Value;
LocalDateTime dateTime = date + time;
return DateTimePattern.Format(dateTime);
}
Note that it might be cleaner to return the LocalDateTime
- do as much of your work as possible in the "natural" representation, only using strings when you really have to.
See more on this question at Stackoverflow