2012-02-09 84 views
-1

我有一个火鸟数据库,有些表有时间戳。例如,我的数据库返回这样的日期:“2012/1/4 3:08:44”或“2011年12月20日4:38:02”。我用TryParseExact和代码如下:火鸟日期无法解析

DateTime.TryParseExact(results[i][1], "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt) 

我试过很多格式,如 “MM/DD/YYYY HH:MM:SS TT”,但没有一次成功。请帮助我,否则我会发疯这一次......

+0

我只是测试你的代码Linqpad迅速,两个字符串(“2012/1/4 3:08: 44 PM“,”12/20/2011 4:38:02 PM“)被成功解析。你能否提供解析失败的另一个例子? – afrischke 2012-02-09 01:11:06

+0

我使用了“G”,它解决了:[链接](http://msdn.microsoft.com/en-us/library/az4se3k1.aspx) – Mehmed 2012-02-09 13:19:41

+0

你确定包含在'resultst [i] [1 ]'还不是DateTime? – 2012-02-09 18:52:16

回答

0

看一看这篇文章

http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

的关键部分看就是

// Parse date-only value without leading zero in month using "d" format. 
// Should throw a FormatException because standard short date pattern of 
// invariant culture requires two-digit month. 
dateString = "6/15/2008"; 
try { 
    result = DateTime.ParseExact(dateString, format, provider); 
    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); 
} 
catch (FormatException) { 
    Console.WriteLine("{0} is not in the correct format.", dateString); 
} 

所以它可能是你的数据库没有返回一个标准模式。看起来很愚蠢,但这会引发异常。在这个例子中,它只是说出一个“仅限日期”的值,而不是你自己的。

如果你有一个字符串的日期,你可以做旧的手工修复行动:

public static string FixDate(string date) 
{ 
    return (date.IndexOf('/') == 1) ? "0" + date : date; 
}