简体   繁体   English

如何将字符串解析为DateTime

[英]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. 我需要使用DateTime.Parse()方法将此字符串解析为System.DateTime TimeReceived变量。

Any one knows how to parse this string? 有人知道如何解析此字符串吗?

You could use the TryParseExact method which allows you to specify a format: 您可以使用TryParseExact方法,该方法允许您指定格式:

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 如果您查看ParseExact函数,大约有一半

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. 那应该工作正常。

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

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