[英]String to Datetime can not convert - C#
我在MSDN中找到了一個將字符串轉換為日期時間的示例。 但這不起作用,請加入catch()。 為什么此代碼塊不起作用?
DateTime dateValue;
string dateString = "2/16/2008 12:15:12 PM";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
您使用的是當前文化中關於日期/時間格式的任何想法-我的猜測是您所處的文化通常是一天出現在一個月之前。
如果您知道格式,我通常會使用不變文化和TryParseExact
絕對不要使用Parse
和catch塊; 使用TryParseExact
或TryParse
。 在這種情況下:
if (DateTime.TryParseExact(dateString, "M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, 0, out dateValue))
{
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
else
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
如果您不知道輸入格式,但是知道要使用的區域性,則只將DateTime.TryParse
與適當的區域性一起使用。
嘗試使用ParseExact
傳遞適當的格式提供程序,如以下示例所示:
string dateString = "2/16/2008 12:15:12 PM";
string format = "M/dd/yyyy hh:mm:ss tt ";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.