【问题标题】:Why is DateTime.TryParse making my number into a Date?为什么 DateTime.TryParse 将我的号码变成日期?
【发布时间】:2014-12-13 05:02:07
【问题描述】:

扩展方法

   public static class DBNullExt
    {
        public static string DBNToString(this object value)
        {
            if (value == System.DBNull.Value)
                return null;
            else
            {
                string val = value.ToString();
                DateTime test;

                if (DateTime.TryParse(val, out test))
                    return test.ToShortDateString();
                else
                    return val;
            }
        }
    }

在哪里使用

            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        dtf.Date1 = rdr["date1"].DBNToString();
                        dtf.Date2 = rdr["date2"].DBNToString();
                        dtf.Cash = rdr["cash"].DBNToString();
                    }
                }
            }    

来自rdr["cash"].DBNToString() 的值是 3685.02。但它不断将数据转换为 3685/2/1。它不应该那样做。而且我不确定它为什么这样做。

【问题讨论】:

  • 因为它掉到了else 并成功地尝试解析它!?它做到了你所要求的。如果您对它的解析方式有疑问,您需要重新考虑 TryParse 的使用或您在此之前的条件。
  • 我猜你的格式是yyyy.MM.,我怀疑。为什么要转换为字符串然后再解析?铸造将是一个更好的主意......就像避免把所有东西都变成一个字符串一般......
  • 您的数据转换非常疯狂。我对你看到这样的效果并不感到惊讶。你最好不要使用这种通用的转换逻辑。您的代码应该知道预期的类型。
  • 当您使用调试器并单步执行代码时会发生什么......?即使看看你在这里有什么data to 3685/2/1 常识会告诉你你做的事情不正确,甚至不是一个有效的日期.. 数据库中的数据类型是什么,引用 Date1 和 Date2 是它存储为TimeStamp 或 int 或其他东西..?你熟悉CASTING 例如dtf.Date1 = (DateTime)rdr["date1"]

标签: c# parsing datetime


【解决方案1】:
public static class DBNullExt
{
    public static string DBNToString(this object value)
    {
        if (value == System.DBNull.Value)
            return null;
        else
        {
            string val = value.ToString();
            DateTime test;

            string format = "MM/dd/yyyy h:mm:ss tt";
            if (DateTime.TryParseExact(val, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out test))
                return test.ToShortDateString();
            else
                return val;
        }
    }
}

作为字符串,3685.022014.10 是允许的 DateTime 格式。上面的代码只解析符合指定格式的字符串形式的 DateTimes。

【讨论】:

    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多