Ask the Expert

Latest date/time before current date/time

How do I calculate the time between the current time in the database? Suppose the date in the database is:

date 22/6 2001
11.30 AM
12.00 PM
4.00 AM

date 23/6/2001
2.00 AM
4.00 AM
5.00 AM

...and the current time is 3.00AM on 23/6/2001. How can I calculate this? The answer should be 2:00AM in this case.


    Requires Free Membership to View

Let's do this two ways -- first, assuming that the dates and times are stored in a single datetime column (as is available in Microsoft SQL/Server), and second, that the dates and times are stored in separate date and time columns.

In the first case, the current date and time are provided as a single value by the SQL/Server GETDATE() function, so the query is really simple --

 select max(theDateTime)
   from theTable
  where theDateTime <= getdate()

In the second case, with separate date and time columns, it's a bit trickier. Standard SQL provides two functions, CURRENT_DATE and CURRENT_TIME, so let's use those (your database may have other functions) --

 select theDate, theTime
   from theTable
  where theDate =
        ( select max(theDate)
            from theTable
           where theDate <= current_date )
    and theTime =
        ( select max(theTime)
            from theTable
           where theDate =
                 ( select max(theDate)
                     from theTable
                    where theDate <= current_date )
             and theTime <= current_time )

This was first published in July 2001

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: