【问题标题】:Trouble parsing string to date c# (from sqlite database)无法将字符串解析为日期 c#(来自 sqlite 数据库)
【发布时间】:2016-08-12 05:12:59
【问题描述】:

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

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 位数之间的任何值。有没有不解析更多手动解析的解决方案?

【问题讨论】:

  • 例外是“System.FormatException”和提示“将字符串转换为DateTIme时,在将每个变量放入DateTime对象之前解析字符串以获取日期。
  • 字符串模式 = "yyyy-MM-dd HH:mm:ss.fff";

标签: c# sqlite datetime


【解决方案1】:

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

DateTime myDate = Convert.ToDateTime(date);

【讨论】:

    【解决方案2】:

    这段代码

            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();
    

    会输出

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

            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 。

    【讨论】:

      【解决方案3】:

      您不能在此处使用DateTime.ParseExact,因为您的毫秒数可以是ffffff 格式之一,这破坏了精确 概念的含义。

      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 设置,您当前的文化可能无法成功解析此字符串,因为@987654335 @ 作为TimeSeparator 和/或不使用GregorianCalendar 作为Calendar 属性。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多