简体   繁体   English

使用DateTime.TryParseExact验证XML Schema dateTime合规性

[英]Using DateTime.TryParseExact to verify XML Schema dateTime compliance

I am trying to verify that a C# string is compliant with XML Schema dateTime format. 我试图验证C#字符串是否符合XML Schema dateTime格式。 Looking at the MSDN, it seems like "o", "s", or "u" standard format strings could all describe valid dateTimes, but I can't get DateTime.ParseExact to work for me. 看看MSDN,似乎“o”,“s”或“u”标准格式字符串都可以描述有效的dateTimes,但我无法让DateTime.ParseExact为我工作。 What am I doing wrong here? 我在这做错了什么?

string myDate = "1999-05-31T13:20:00.000-04:00";
DateTime.ParseExact(myDate, "o", CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime.ParseExact(myDate, "s", CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime.ParseExact(myDate, "u", CultureInfo.InvariantCulture, DateTimeStyles.None);

None of the above work. 以上都不是。 Sorry if my formatting is bad: first time posting a question here. 对不起,如果我的格式不好:第一次在这里发布一个问题。

Since you want to test that the data is XML compliant, you could use the XmlConvert.ToDateTime method: 由于您要测试数据是否符合XML,因此可以使用XmlConvert.ToDateTime方法:

DateTime dt = XmlConvert.ToDateTime(myDate);

This will throw a FormatException if the given string does not have the correct format. 如果给定的字符串没有正确的格式,这将抛出FormatException

Just use XmlConvert.ToDateTime (note that XmlConvert.ToDateTime(string) is considered obsolete now and you should use XmlConvert.ToDateTime(string, XmlDateTimeSerializationMode) . 只需使用XmlConvert.ToDateTime (注意XmlConvert.ToDateTime(string)现在被认为是过时的,你应该使用XmlConvert.ToDateTime(string, XmlDateTimeSerializationMode)

However, if you insist on using DateTime.ParseExact (and there are good reasons to do so but then you should use DateTime.TryParseExact to avoid exception throwing in cases of fail) you can use the following format string: 但是,如果您坚持使用DateTime.ParseExact (并且有充分的理由这样做,但是您应该使用DateTime.TryParseExact来避免在失败的情况下抛出异常),您可以使用以下格式字符串:

string format = "yyyy-MM-ddTHH:mm:ss.fffzzz";

The parentheticals in the above paragraphs might be cumbersome to parse (I have a habit of doing that; sorry). 上面段落中的括号内容可能很难解析(我有这样做的习惯;对不起)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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