无法将字符串转换为DateTime

本文关键字:DateTime 转换 字符串 | 更新日期: 2023-09-27 17:59:49

在函数内部,我需要在几秒内找到两个日期之间的差异。如果差异超过30秒,我将返回False,否则返回True。第一个是我从数据库中读取的,第二个是当前DateTime。现在

以下是我正在使用的代码片段,它在dr.GetValue(0).ToString()保存数据库中的当前值时完成工作:

if (dr.Read())
            {
                DateTime nowDate = Convert.ToDateTime(DateTime.Now.ToString("M/dd/yyyy H:mm:ss tt"));
                DateTime then = DateTime.ParseExact(dr.GetValue(0).ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
                TimeSpan diff = nowDate - then;
                int timeDifference = diff.Seconds;

                if (timeDifference > 30)
                {
                    myConn.Dispose();
                    return false;
                }
                else {
                    myConn.Dispose();
                    return true;
                }
            }

当我执行上面的代码时,我得到一个消息错误:
string was not recognized as valid DateTime

这是导致错误的一行:

 DateTime then = DateTime.ParseExact(dr.GetValue(0).ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);

时间以以下格式存储在数据库中:2013-02-18 14:06:37

但当我执行以下行时(出于调试目的):

MessageBox.Show(dr.GetValue(0).ToString());

我看到一个显示日期的消息框,格式如下:2/18/2013 2:06:37 PM

如何查找当前时间与dr.GetValue(0).ToString()中存储的时间之间的秒差

如有任何帮助,将不胜感激

无法将字符串转换为DateTime

您想要的是h,而不是Hh是12小时格式的小时,H是24小时格式的时间。由于您的示例小时是2 PM(而不是14 PM),因此它是您想要的12小时格式。

还有:

  • 你正在将你现在的时间转换为字符串并返回-别担心
  • 你计算的是Seconds而不是TotalSeconds——这是不正确的,因为例如60秒的周期给出的Seconds值为0
DateTime nowDate = DateTime.Now;
DateTime then = DateTime.ParseExact(
    dr.GetValue(0).ToString(), "M/dd/yyyy h:mm:ss tt",
    CultureInfo.InvariantCulture);
TimeSpan diff = nowDate - then;
double secondsDifference = diff.TotalSeconds;

你甚至应该能够做一些类似的事情

DateTime then = dr.GetDateTime(0);

并完全避免字符串解析,但H/h的差异是您得到所询问的特定异常的原因。

如果您的日期是数据库中的日期时间,您可能会将这两行简化为:

DateTime nowDate = DateTime.Now;
DateTime then = (DateTime)dr.GetValue(0);

(尽管我在这里做了很多假设)

您的代码应该非常简单:

if (dr.Read())
{
    DateTime then = dr.GetDateTime(0);
    TimeSpan diff = DateTime.Now - then;
    int timeDifference = diff.TotalSeconds;
}

需要注意的一点是,您真的不应该在if/else中调用myConn.Dispose();。用using语句包装您的联系和读者。

我认为您的服务器已经设置了应用程序服务器的其他日期格式。你可以试试这个:

Convert.ToDate(value,System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormate);

希望这能解决错误。还没有测试过,所以希望最好