2016-03-15 59 views
2

我必须用c#验证DateTime。 所以我建立这个代码:如果我用这个日期如何验证DateTime

2016年6月9日11

private const string Format = "yyyy-MM-dd hh:mm:ss.fff"; 
public object ValidDate(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
{ 
    if (reader.Value == null) 
    { 
    return null; 
    } 

    var s = reader.Value.ToString(); 
    DateTime result; 
    if (DateTime.TryParseExact(s, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) 
    { 
    return result; 
    } 

    return DateTime.Now; 
} 

现在:20:50.125

它是确定的,但如果我尝试使用此日期

2016年6月9日13:20:50.125

不是日期是valide。问题在一小时。从1到12没关系。从13日到24日不好。 我该如何修复它?

+0

你可以参考这个 - http://stackoverflow.com/questions/9785162/how-to-format-datetime-to-24-hours-time – Shanid

+0

顺便说一句,在C#中,有没有'24:00'表示。与其他现代世界语言/应用程序一样,它被表示为'00:00'。阅读:[中午和午夜混乱](https://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight)和[午夜00:00和24:00](https://en.wikipedia.org/维基/ 24 hour_clock#Midnight_00:00_and_24:00)。 –

+0

同样来自[ISO8601](https://en.wikipedia.org/wiki/ISO_8601#Times):'Midnight'是一种特殊情况,可以称为“00:00”或“24: 00" '。在日历日的开始处使用符号“00:00”,并且使用得更频繁。在一天结束时使用'“24:00”'。 '“2007-04-05T24:00”'和“2007-04-06T00:00”一样 –

回答

1

在传递给DateTime.TryParseExact()格式的hh预计12小时格式的小时。

如果以24小时格式有时间,你必须将其更改为HH

private const string Format = "yyyy-MM-dd HH:mm:ss.fff"; 
0

你的格式字符串

yyyy-MM-dd hh:mm:ss.fff 

hh指定要在12小时内 使用表示时间HH而不是hh,它应该如你所期望的那样工作