Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the last possible time of a particular day

Tags:

I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?

like image 606
test Avatar asked Oct 03 '08 15:10

test


People also ask

How do I get the last time of the day in SQL?

The answer is SELECT DATEADD(ms, -3, '2008-01-24') , the explanation is below. Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG-ability of the query, which means indexes that might have been used aren't. This is great!

What is SQL Getdate?

SQL Server GETDATE() Function The GETDATE() function returns the current database system date and time, in a 'YYYY-MM-DD hh:mm:ss. mmm' format.

Which query is used to get the current date in SQL?

MySQL SYSDATE() Function The SYSDATE() function returns the current date and time.


1 Answers

The answer is SELECT DATEADD(ms, -3, '2008-01-24'), the explanation is below.

From Marc's blog:

But wait, Marc... you said you like to use BETWEEN, but that query doesn't have one... that's because BETWEEN is inclusive, meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly NOT by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL Server DATETIME columns have at most a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:

    SELECT DATEADD(ms, -3, DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0)) 

So to do the orders due this month as a BETWEEN query, you can use this:

    SELECT [ID]     FROM [dbo].[Orders]     WHERE [ShipDue] BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()), 0)     AND DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GetUTCDate()) + 1, 0)) 

Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG-ability of the query, which means indexes that might have been used aren't.

like image 175
bdukes Avatar answered Sep 25 '22 11:09

bdukes