简体   繁体   English

如何使用特定格式将字符串解析为DateTime?

[英]How do I parse a string into a DateTime, with a specific format?

I have a source where dates comes in this string form: 我有一个来源,其中日期以这种字符串形式出现:

   Sat Sep 22 13:15:03 2018

Is there an easy way I can parse that into a DateTime in C#? 有没有一种简单的方法可以解析为C#中的DateTime? I've tried with DateTime.(Try)Parse, but it doesn't seem to recognize this specific format... 我尝试过DateTime。(尝试)Parse,但它似乎没有认识到这种特定的格式...

You should prefer DateTime.ParseExact and TryParseExact ; 你应该更喜欢DateTime.ParseExactTryParseExact ; these methods let you specify the expected format(s) in your program. 这些方法允许您指定程序中的预期格式。

The DateTime.Parse and TryParse methods are dangerous because they accept the current date/time format configured on the machine where the code is running -- which the user can change from the default -- along with a couple of culture-neutral formats. DateTime.ParseTryParse方法很危险,因为它们接受在运行代码的机器上配置的当前日期/时间格式 - 用户可以从默认值更改 - 以及一些与文化无关的格式。 In other words, the user can change settings in Control Panel and break Parse / TryParse . 换句话说,用户可以更改控制面板中的设置并中断Parse / TryParse

Try DateTime.ParseExact 尝试DateTime.ParseExact

This code takes your date string and applies a format to create a DateTime object. 此代码采用您的日期字符串并应用格式来创建DateTime对象。

CultureInfo provider = CultureInfo.InvariantCulture;

string dateString = "Sat Sep 22 13:12:03 2018";
string format = "ddd MMM dd HH':'mm':'ss yyyy";

DateTime result = DateTime.ParseExact(dateString, format, provider);

这有效:

DateTime dt = DateTime.ParseExact ("Sat Sep 22 13:15:03 2018", "ddd MMM d HH:mm:ss yyyy", null)
var str = "Sat Sep 22 13:15:03 2018";
var date = DateTime.ParseExact(str, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);

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

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