无法解析字符串到日期c#(来自sqlite数据库)

时间:2016-04-19 20:01:07

标签: c# sqlite datetime

我为许多其他帖子的答案建模了解决方案,但它仍然不起作用。

public void dtParsing()
{
    string date = "2016-04-19 15:14:19.597";
    Console.WriteLine("date as C# string : {0} : ", date);
    string pattern = "yyyy-M-d H:m:s.f";
    DateTime myDate = DateTime.ParseExact(date, pattern, null);
    Console.WriteLine("\ndate as C# datetime : {0} : ", myDate.ToString());
    Console.ReadKey();
}

一个问题是值不是设定的位数:毫秒可以是从0到3位的任何位数。有没有解析更多手动解析的解决方案?

3 个答案:

答案 0 :(得分:0)

这应该可以阻止错误(不需要模式,必须完全匹配)

DateTime myDate = Convert.ToDateTime(date);

答案 1 :(得分:0)

此代码

        string date = "2016-04-19 15:14:19.597";
        Console.WriteLine("date as C# string : {0} : ", date);
        DateTime myDate = Convert.ToDateTime(date);
        Console.WriteLine("\ndate as C# datetime : {0} : ", myDate.ToString());
        Console.ReadKey();

将输出

screenshot of code output

或者您可以保留字符串模式并获得相同的结果

        string date = "2016-04-19 15:14:19.597";
        Console.WriteLine("date as C# string : {0} : ", date);
        string pattern = "yyyy-MM-dd HH:mm:ss.fff";
        DateTime myDate = DateTime.ParseExact(date, pattern, null);
        Console.WriteLine("\ndate as C# datetime : {0} : ", myDate.ToString());
        Console.ReadKey();

是毫秒可以是0到3位数之间的任何位置,但实际上毫秒总是3位数。像这样:5毫秒实际上是.005。

答案 2 :(得分:0)

您不能在此处使用DateTime.ParseExact,因为您的毫秒可以是ffffff格式之一,这会破坏 exact concept。

DateTime.Parse可以使用InvariantCulture正确的文化成功解析您的字符串。

DateTime dt;
dt = DateTime.Parse("2016-04-19 15:14:19", CultureInfo.InvariantCulture);
// Successfull
dt = DateTime.Parse("2016-04-19 15:14:19.5", CultureInfo.InvariantCulture);
// Successfull
dt = DateTime.Parse("2016-04-19 15:14:19.59", CultureInfo.InvariantCulture);
// Successfull
dt = DateTime.Parse("2016-04-19 15:14:19.597", CultureInfo.InvariantCulture);
// Successfull

请注意,使用null作为IFormatProvider 可能会让人感到困惑,因为这意味着它应该使用CurrentCulture设置,您当前的文化可能无法使用成功解析此字符串由于:TimeSeparator和/或未使用GregorianCalendar作为Calendar属性。

例如,ar-SA文化无法解析您使用UmAlQuraCalendar作为Calendar的字符串。