Inside a function, I need to find the difference between 2 dates in seconds. If the difference is more than 30 seconds i return False otherwise it returns True , first one I read it from database and Second one is the current DateTime.Now
Here is the snippest of code I’m using that does the work while dr.GetValue(0).ToString() holds the current value in the database :
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;
}
}
When i execute the code above i get a message error :
string was not recognized as valid DateTime
And here is the line that is causing the error :
DateTime then = DateTime.ParseExact(dr.GetValue(0).ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
The time is stored in the database in this format : 2013-02-18 14:06:37
But when I execute the following line (for debugging purposes) :
MessageBox.Show(dr.GetValue(0).ToString());
I see a message box that shows the date in this format : 2/18/2013 2:06:37 PM
How to find the difference in seconds between the current time and the time stored in dr.GetValue(0).ToString()
Any help would be highly appreciated
You want
h, notH.his the hour in 12-hour format,His the hour in 24-hour format. Since your example hour is2 PM(not14 PM) it’s the 12-hour format you want.Also:
SecondsnotTotalSeconds– this is incorrect because e.g. a 60-second period gives aSecondsvalue of0.You should even be able to do something along the lines of
and avoid the string-parsing altogether, but the
H/hdifference is the reason you get the specific exception you asked about.