2013-02-18 200 views
0

函数内部,我需要在几秒钟内找到两个日期之间的差异。如果差值超过30秒,我回到否则返回,我第一个从数据库中读取它,第二个是当前DateTime.Now无法将字符串转换为DateTime?

这里是snippest的代码,我使用该做的工作,而dr.GetValue(0).ToString()保存数据库中的当前值:
string was not recognized as valid DateTime

和:

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; 
       } 
      } 

当我在上面,我得到一个消息,错误执行代码这里是导致该错误的行:

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

如何找到CURR之间以秒之差耳鼻喉科时间和存储在dr.GetValue(0)的ToString(时间)

任何帮助将高度赞赏

+0

你为什么使用'DateTimes'字符串?使用参数。 – 2013-02-18 14:35:50

+4

你为什么要将'DateTime.Now'转换成一个字符串,然后转换回'DateTime'?你为什么不从数据库查询中返回一个'DateTime'? – 2013-02-18 14:36:15

+0

不是你的数据库中的日期时间,好吧,日期时间? – baldric 2013-02-18 14:37:03

回答

3

你想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不同的是,你得到的原因具体的例外,你问。

0

我认为你的服务器有应用程序服务器有一些其他的日期格式集。你可以试试这个:

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

希望这将解决该错误。没有测试它因此希望获得最佳

1

如果,因为它看起来像,你的日期是在数据库中的日期时间,你也许可以简化两行这样的:

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

(虽然我中号做了很多假设这里)

1

你的代码真的应该很简单:

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

需要注意的一点 - 你真的不应该在你的来调用。将您的连接和阅读器封装在using声明中。