简体   繁体   中英

Error, String not recognized as valid DateTime when trying to ParseExact time string

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM