C# datetime.parse 并使其以特定格式工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/341175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:51:48  来源:igfitidea点击:

datetime.parse and making it work with a specific format

c#asp.net.net-2.0

提问by anonym0use

I have a datetime coming back from an XML file in the format:

我有一个从 XML 文件返回的日期时间,格式如下:

20080916 11:02

20080916 11:02

as in

yyyymm hh:ss

yyyymm hh:ss

How can i get the datetime.parse function to pick up on this? Ie parse it without erroring? Cheers

我怎样才能得到 datetime.parse 函数来解决这个问题?即解析它没有错误?干杯

采纳答案by Blair Conrad

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

假设你的意思是说分钟跟随小时,而不是秒 - 你的例子有点令人困惑。

The ParseExact documentationdetails other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

ParseExact文档详细说明其他重载,如果你想拥有解析自动转换为通用时间或类似的东西。

As @Joel Coehoornmentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

正如@Joel Coehoorn提到的,还有使用TryParseExact的选项,它将返回一个指示操作成功或失败的布尔值 - 我仍在使用 .Net 1.1,所以我经常忘记这个。

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

如果您需要解析其他格式,您可以查看标准日期时间格式字符串

回答by bert

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

感谢您的提示,我用它来解析我的日期“20071122”,我需要添加日期时间样式,我没有使用它并且它有效:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);