2012-08-17 79 views
0

我試圖解析字符串(從充滿英語的日期格式一個文本框)使用此代碼爲DateTime:DateTime.TryParse解析錯誤的格式

DateTime dt; 
if (DateTime.TryParseExact(Text, DateTimeFormat, System.Threading.Thread.CurrentThread.CurrentCulture, DateTimeStyles.AssumeLocal, out dt)) 
{ 
    logger.Trace("LOCALE: {0} ", System.Threading.Thread.CurrentThread.CurrentCulture); 
    logger.Trace("DateTimeFormat: {0} ", DateTimeFormat); 
    logger.Trace("CurrentCulture ShortDatePattern: {0} ", System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern); 
    logger.Trace("Text: {0} ", Text); 
    logger.Trace("result of TryParse: {0} ", dt); 
    return dt; 
} 

但是在我的記錄器輸出爲:

LOCALE: en-US 
DateTimeFormat ShortDatePattern: M/d/yyyy 
CurrentCulture ShortDatePattern: M/d/yyyy 
Text: 8/31/2012 
result of TryParse: 31-8-2012 0:00:00 

我完全卡住爲什麼會發生這種情況。

在一個單獨的控制檯應用程序中使用此代碼的工作:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); 
string text = @"8/31/2012"; 
DateTime date; 
string dateTimeFormat = @"M/d/yyyy"; 
bool parseOk = DateTime.TryParseExact(text, dateTimeFormat, Thread.CurrentThread.CurrentCulture, DateTimeStyles.AssumeLocal, out date); 

額外的信息:

  • 系統:Windows 7旗艦版EN
  • 非Unicode系統語言:英語
  • web.config system.web:

問題: 問題是我想要的日期是在格式爲「M/d/YYYY」,而是它被解析爲「DD-MM-YYYY」

+0

我沒有看到你的記錄任何錯誤。文本正確解析...出了什麼問題?或者您想以格式M/d/yyyy再次在記錄器中打印日期時間? – JleruOHeP 2012-08-17 11:30:56

+0

什麼是錯的,在我看來,日期被正確解析。 – 2012-08-17 11:31:56

+1

其格式問題。 OP要M/DD/YYYY,但輸出爲DD-M-YYYY – 2012-08-17 11:33:01

回答

3

您還沒有導致無效日期爲日誌條目指定了一個輸出字符串,因此它將使用默認值(基於當前文化)。

因此,而不是:

logger.Trace("result of TryParse: {0} ", dt); 

用途:

logger.Trace("result of TryParse: {0} ", dt.ToString("M/dd/yyyy")); 

或者:

logger.Trace("result of TryParse: {0} ", dt.ToShortDateString());