错误,在尝试ParseExact时间字符串时,字符串未被识别为有效的DateTime

Day*_*yan 2 c# datetime

执行突出显示的行后,以下操作失败.

在此输入图像描述

字符串未被识别为有效的DateTime.

它突然发生,在12点左右工作......?现在是下午4:54而且没有去.到底他妈发生了什么?

Jon*_*eet 7

您应该使用hh:mm:ss tt格式字符串 - HH用于24小时制,此时您说它是4AM ...但是PM作为AM/PM指示符.

基本上,使用hhtt,或HH自身.

使用Noda Time,您将使用:

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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,返回可能更干净LocalDateTime- 在"自然"表示中尽可能多地完成工作,只在必要时使用字符串.