我有以下格式如何將字符串分析爲DateTime
Thu Jan 5 19:58:58 2012
我需要這個字符串解析到System.DateTime
TimeReceived
使用可變DateTime.Parse()
方法的字符串的日期。
任何人都知道如何解析這個字符串?
我有以下格式如何將字符串分析爲DateTime
Thu Jan 5 19:58:58 2012
我需要這個字符串解析到System.DateTime
TimeReceived
使用可變DateTime.Parse()
方法的字符串的日期。
任何人都知道如何解析這個字符串?
你可以使用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);
}
var reformatted = input.Substring(4, 17) + input.Substring(22);
return DateTime.Parse(reformatted);
這應該很好地工作。
,如果你看一下ParseExact功能,大約一半有
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
因此,如果你想切換周圍的人,以匹配你想要什麼,你會
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);
}
這是什麼提供商? – Sowmya 2012-01-05 15:26:52
哦,沒有看到那個參數。修復了代碼,它只是CultureInfo.InvariantCulture – 2012-01-05 15:33:11
你剛剛結束了想要時間部分?你試過什麼了? – keyboardP 2012-01-05 15:14:31
請顯示一些代碼...你有什麼試過?什麼不起作用? – Yahia 2012-01-05 15:14:56
查看「DateTime.ParseExact」和「TryParseExact」。這裏存在很多涉及這兩種方法的問題。 – 2012-01-05 15:15:38