I am a little confused about how or what the best way to determine what the closest date is to DateTime.Now
is.
In my table, everything needs to be timestamped. And on a page, I need to be able to retrieve everything from the table only if the date is the closest date to now.
How would I go about this?
I am using DateTime.Now
when inserting dates into the Database, and the format is like:
5/07/2011 5:28:57 PM
Here's my suggestion:
declare @DateTimeNow datetime = getdate()
select TOP (1)
RecordId
,MyDateColumn
,abs(datediff(s, MyDateColumn, @DateTimeNow)) as Diff
from
MyTable
order by
abs(datediff(s, MyDateColumn, @DateTimeNow)) asc
Do not forget to use ABS()!
Do you only have past dates, meaning, will you ever have a date that is newer than DateTime.Now
? If not, you could get by with a simple Order By
on the date column selecting the newest date. Otherwise, you'll need to get a date difference between your DateTime.Now
, and order by that result. eg
SELECT TOP 1
columnDate
FROM table1
ORDER BY DATEDIFF (ss,@passedInDate,columnDate)
This would essentially look for all future and past dates using your @passedInDate (DateTime.Now) as the qualifier or base date. I'm using seconds as the time interval to compare in my example, but you can change that to whatever makes the most sense for you.
Also, you shouldn't need to pass in DateTime.Now
to SQL server, as you can use the built in GetDate()
function.
How about
SELECT TOP 1 *
FROM MyTable
ORDER BY TimestampColumn DESC
Consider storing time in UTC - DateTime.UtcNow
In T-SQL you could use DateDiff:
DATEDIFF ( datepart , startdate , enddate )
http://msdn.microsoft.com/en-us/library/ms189794.aspx
or in C# you could use TimeSpan:
http://msdn.microsoft.com/en-us/library/system.timespan.aspx#Y3719
Something like this should work:
SELECT TOP 1 * FROM MyTable ORDER BY ABS(DATEDIFF(DD, getdate(), DATE))
This should sort your rows by the closest date, past or future. If you need it more precise then just days, change DD to something else, as specified here
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.