简体   繁体   中英

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#? I've tried with DateTime.(Try)Parse, but it doesn't seem to recognize this specific format...

You should prefer DateTime.ParseExact and TryParseExact ; 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. In other words, the user can change settings in Control Panel and break Parse / TryParse .

Try DateTime.ParseExact

This code takes your date string and applies a format to create a DateTime object.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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