简体   繁体   中英

How to parse a string to DateTime

i have a string date in the following format

 Thu Jan  5 19:58:58 2012

I need to parse this string to System.DateTime TimeReceived variable using DateTime.Parse() method.

Any one knows how to parse this string?

You could use the TryParseExact method which allows you to specify a format:

var str = "Thu Jan 5 19:58:58 2012";
DateTime date;
if (DateTime.TryParseExact(str, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    // the date was successfully parsed, you could use the date variable here
    Console.WriteLine("{0:HH:mm:ss dd/MMM/yy}", date);
}

if you look at the ParseExact function, about halfway there's

dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";

so if you'd switch those around to match what you want, you'll end up with

CultureInfo provider = CultureInfo.InvariantCulture;

// Parse date and time with custom specifier.
dateString = "Thu 5 Jan 19:58:58 2012";

format = "ddd MMM dd hh:mm:ss yyyy";
try {
   result = DateTime.ParseExact(dateString, format, provider);
   Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
   Console.WriteLine("{0} is not in the correct format.", dateString);
}
var reformatted = input.Substring(4, 17) + input.Substring(22);
return DateTime.Parse(reformatted);

That should work fine.

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