2015-09-03 112 views
1

我有以下代碼。我想要做的是如果它是一個空值的日期返回NULL或返回短日期。例如:12/12/15。我得到一個錯誤:將字符串轉換爲shortdate時間

When converting a string to DateTime parse the string to take the date before putting each variable into the DateTime Object.

public DateTime? StrToDate(string val) 
{  
    DateTime? dt = string.IsNullOrEmpty(val) 
     ? (DateTime?)null 
     : DateTime.ParseExact(val, "MM/dd/yyyy", null);  
    return dt; 
} 
+0

你傳遞給函數的字符串是什麼? – JoaoFSA

+2

首先,你究竟在哪裏得到那個錯誤?這並非我見過的錯誤。其次,你在一年中傳遞2位數字,但解析方法顯式尋找4。 – DavidG

回答

2

多一點前途的解決方案是使用TryParseExact()。 TryParseExact或ParseExact的情況也是,它只接受提供的字符串格式以將其解析爲DateTime。

public static DateTime? StrToDate(string val) 
    { 
     CultureInfo enUS = new CultureInfo("en-US"); 
     DateTime dateValue; 
     if (DateTime.TryParseExact(val, "MM/dd/yyyy", enUS, 
            DateTimeStyles.AllowWhiteSpaces, out dateValue)) 
     { 
      return (dateValue); 
     } 
     else 
     { 
      return null; 
     } 
    } 

現在測試用例是這樣的:

 // Valid date 
     var date = StrToDate("05/01/2000"); 

     // Null 
     var nulldateFromEmpty = StrToDate(string.Empty); 

     // Null 
     var nullDateFromNullString = StrToDate(null); 

更新:如果你希望確切地恢復的情況下「15年12月12日」,則DateTime對象表示與結構所有日期和時間字段,所以即使從ShortDateTime字符串(12/12/15)解析值,該對象仍然具有時間的默認值,即「12:00:00 AM」。要轉換這些值可以再次調用var date = StrToDate("05/01/2015").Value.ToString("MM/dd/yy");

-1

試試這個:

VAR日期時間= Convert.ToDateTime( 「1992年11月25日」);

return datetime.ToShortDateString();