简体   繁体   English

C#,如何从存在于字符串对象中的日期时间构建DateTime对象?

[英]C# , How can i build a DateTime object from a datetime present in a string object?

在C#中,如何从字符串对象中存在的日期时间(字符串strDate =“ 2009/11/11”)构建DateTime对象?

Have a look at the DateTime.Parse or DateTime.ParseExact methods. 看一下DateTime.ParseDateTime.ParseExact方法。

Simplest case: 最简单的情况:

var result = DateTime.Parse(str);

There's also DateTime.ParseExact which is also worth knowing about. 还有DateTime.ParseExact ,这也是值得了解的。

There's also TryParse and TryParseExact which do the same thing, but won't throw an exception if the date is not valid - will just return a bool. 还有TryParseTryParseExact可以做同样的事情,但是如果日期无效,则不会抛出异常-只会返回布尔值。

Using that string format will give you a lot of issues later, such as what is "03/04/2009"? 使用该字符串格式将在以后给您带来很多问题,例如什么是“ 03/04/2009”?

try using DateTime.ParseExact . 尝试使用DateTime.ParseExact

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

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