2013-07-10 40 views
0

好日子其他日期時間,測試字符串轉換爲比DateTime.TryParseExact

通常情況下,如果我想測試一個字符串是否是一個有效的日期時間格式,我會用:

if (DateTime.TryParseExact()){ 
//do something 
} 

我想問一下,有沒有什麼代碼可以直接測試Convert.ToDateTime()是否成功? 例如像:

if (Convert.ToDateTime(date1)){ 
//do something 
} 

if(Convert.ToDateTime(date1) == true){ 
//do soemthing 
} 

我的想法是使之成爲布爾測試它的成功轉換爲日期時間或沒有。 只是想找出代碼,而不是使用DateTime.TryParseExact()

+4

DateTime.TryParseExact有什麼問題? –

+0

用'try..catch'包裝你的代碼 –

+1

不使用DateTime.TryParse或DateTime.TryParseExact的特殊原因?這正是他們在那裏的原因。 – Corak

回答

4

你的第一個代碼

if (DateTime.TryParseExact()) { 
    //do something 
} 

不正是你想要的。

使用方法如下:

if (DateTime.TryParseExact(str, ...)) { // OR use DateTime.TryParse() 
    // str is a valid DateTime 
} 
else { 
    // str is not valid 
} 

您可以使用DateTime.TryParse()如果你不想提供的格式。
這兩種方法都返回一個bool ean值。

+0

我明白你的意思。如果使用'DateTime.TryParseExact(str,format,...)',我需要聲明一個格式來檢查。 我的問題是,我可以傳遞'Convert.ToDateTime(str)'成爲布爾或不布爾。 –

+0

@PanadolChong:如前所述,您也可以使用'DateTime.TryParse()',而不必提供格式。 – joe

0

按照您的意見:

我需要聲明的格式檢查,有時日期時間格式可能不同,這就是爲什麼我在想有沒有像我所想的任何代碼。

TryParseExact已採取格式。

這個簡短的例子,你想用TryParseExact。如果格式或日期錯誤,TryParseExact不會引發異常,因此您不必擔心昂貴的Try/Catch區塊。相反,它將返回false

static void Main() 
{ 
    Console.Write(ValidateDate("ddd dd MMM h:mm tt yyyy", "Wed 10 Jul 9:30 AM 2013")); 
    Console.Read(); 
} 

public static bool ValidateDate(string date, string format) 
{ 
    DateTime dateTime; 
    if (DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) 
    { 
     Console.WriteLine(dateTime); 
     return true; 
    } 
    else 
    { 
     Console.WriteLine("Invalid date or format"); 
     return false; 
    } 
} 

或縮短:

public static bool ValidateDate(string date, string format) 
{ 
    DateTime dateTime; 
    return DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime); 
} 
-1

然後使用這樣的事情。

bool isDateTimeValid(string date, string format) 
{ 
    try 
    { 
     DateTime outDate = DateTime.ParseExact(date, format, Thread.CurrentThread.CurrentUICulture); 

     return true; 
    } 
    catch(Exception exc) 
    { 
     return false; 
    } 
} 
+0

'DateTime.TryParseExact(...)'不會引發異常。你是不是指'DateTime.ParseExact'? – joe

+0

被編輯,是的,我想使用ParseExact –

+0

,但這正是'TryParseExact'的作用...... – joe

2

如果你真的想要你可以使用轉換爲。然而,使用這意味着你不會得到tryparse可以給你的功能。

的TryParse:

- 簡單的if/else驗證

-Wont玉石俱焚您的應用程序,如果錯誤數據被放入它

public static bool 
{ 
    TryParse(string s, out DateTime result) 
} 

那麼如果其他驗證

轉換爲:

- 如果錯誤數據放進去,你的應用程序會崩潰

- 更好地爲包括嘗試捕捉到這個

- 見的msdn article on ConvertTo

private static void ConvertToDateTime(string value) 
{ 
    DateTime convertedDate; 
    try { 
    convertedDate = Convert.ToDateTime(value); 
    Console.WriteLine("'{0}' converts to {1} {2} time.", 
         value, convertedDate, 
         convertedDate.Kind.ToString()); 
    } 
    catch (FormatException) { 
    Console.WriteLine("'{0}' is not in the proper format.", value); 
    } 
} 

在我眼裏,你應該始終偏好Tryparse。