简体   繁体   中英

Comparing DateTime.Now to value stored in SQL

I am converting ADODB namespace code to SqlClient . I am trying to replace code that utilized recordset.Value . I am having problems converting this line of code. How can I subtract DateTime.Now from the value in the time_of_lock (Datetime data type) column in SQL ?

else if (DateTime.Now - rs.Fields["time_of_lock"].Value < TimeSpan.FromMinutes(15))

I am assuming you can get two DateTime values from your code. If so, try pop both into the following function:

private bool TimesApartNoMoreThan(DateTime first, DateTime second, int threshold) 
{
    return (second - first).TotalMinutes > threshold;
}

when you subtract two DateTimes, you get a TimeSpan . Having obtained that, you can represent it as whatever unit of duration you need ( in this case, minutes ):

From your statement, I am assuming rs.Fields["time_of_lock"] is of DateTime datatype. If that is the case, please try this:

DateTime.Now .Subtract(rs.Fields["time_of_lock"].Value).TotalMinutes < 15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM