简体   繁体   中英

Convert DateTime from strange format to DateTime object

Normally converting DateTime from string is pretty easy, however I encountered this format :

Mon Jan 05 17:38:34 +1100 2015

which seems quite bizarre and also causes DateTime.Parse() to fail. All of the elements are there. Is there a way to convert this to DateTime without doing a string.split(" ") to divide it up into chunks. It does look like it could be an ISO standard although what standard is beyond me.

To clarify, I would like some assistance in converting the above sample string into a DateTime object in .NET using C# , and would prefer to do it without dividing the string if possible.

(@editors, why would you approve an edit changing a sentence with a pause into a run-on sentence that is bad english ? pls stop editing for the sake of epeen on edits -.- )

You can specify the exact format:

var text = "Mon Jan 05 17:38:34 +1100 2015"
var date = DateTime.ParseExact(text, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);

As noted in comments, the lesser seen zzz part represents the offset from UTC . For this reason, you may prefer to parse with DateTimeOffset (using the same format string) as it handles this concept better than DateTime . Your requirements may not allow this, however.

This works for me:

var dt = "Mon Jan 05 17:38:34 +1100 2015";

DateTime result;
DateTime.TryParseExact(dt, "ddd MMM dd HH:mm:ss zzzz yyyy", 
    CultureInfo.InvariantCulture, DateTimeStyles.None,  out result);

Console.WriteLine(result);

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