最近碰到一個這樣的問題:我從一個控制項中擷取時間值的字串,然後把這個字串轉化成DateTime對象,在控制項中顯示的時間值是: 2005-06-07 12:23:34分,但是我通過一個函數去擷取這個值後,得到的是2005-6-7 12:23:34,因此當設定時間格式為: yyyy-MM-dd HH:mm:ss 去調用DateTime::ParseExact函數的時候就出現了異常,提示是時間格式不匹配。這就提醒我們,在設定時間格式後,調用DateTime::ParseExact去把一個字串轉成DateTime對象,必須保證這個字串的格式和我們設定的要轉換的時間格式一致,否則就會有異常。
//下面這段程式就會出現異常,異常提示為:字串未被識別為有效DateTime.
using System.Globalization;
namespace _3
{
class Class1
{
static void Main(string[] args)
{
string mytime = "2005-6-7 12:23:34";
IFormatProvider culture = new CultureInfo("zh-CN", true);
//期望的時間格式為月,日必須為兩位,不足兩位,左邊應該填0補充
string[] expectedFormats = {"yyyy-MM-dd HH:mm:ss"};
DateTime dt =
DateTime.ParseExact(mytime,
expectedFormats,
culture,
DateTimeStyles.AllowInnerWhite);
Console.WriteLine("dt = {0}", dt);
}
}
}
改正的方法有兩個:
1. string mytime = "2005-6-7 12:23:34"; 改為: string mytime = "2005-06-07 12:23:34";
2. 期望的格式從string[] expectedFormats = {"yyyy-MM-dd HH:mm:ss"}; 改為: string[] expectedFormats = {"yyyy-M-d HH:mm:ss"};
//下面這段代碼可以匹配毫秒.
using System;
using System.Globalization;
namespace _3
{
class Class1
{
static void Main(string[] args)
{
string mytime = "2005-6-7 12:23:34.123";
IFormatProvider culture = new CultureInfo("zh-CN", true);
string[] expectedFormats = {"yyyy-M-d HH:mm:ss.fff"};
DateTime dt =
DateTime.ParseExact(mytime,
expectedFormats,
culture,
DateTimeStyles.AllowInnerWhite);
Console.WriteLine("dt = {0},毫秒: {1} ", dt,dt.Millisecond);
}
}
}
輸出的結果為: dt = 2005-6-7 12:23:34 ,毫秒: 123