Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DateTime with time as 23:59:59

Tags:

date

sql

datetime

I'm trying to do a where statement that specifies a DateTime field is between the start and end of the previous month.

To do this, I need to specify that the first day of the previous month has a time of 00:00:00 and the last day of the previous month has a time of 23:59:59.

This second condition is giving me a headache..

Can someone help me out?

Cheers

MSSQL 2008

like image 401
Matt Avatar asked Jul 21 '11 03:07

Matt


People also ask

How do you set the date 23 59 59?

string dt1 = DateTime. Now. ToString("yyyy-MM-dd 23:59:59.000"); Also in your case if suppose your input datetime having any hour/minute details then adding timespan could give wrong results, but if you hardcode as i have done above it will always return date in your required way.

How do I convert datetime to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.

Does Getdate () include time?

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


2 Answers

try:

SELECT DATEADD(ms, -3, '2011-07-20')

This would get the last 23:59:59 for today.

why 3 milliseconds?, this is because 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

like image 148
Oscar Gomez Avatar answered Sep 17 '22 07:09

Oscar Gomez


You can also use the less than '<' without the equal. So that you don't need 23:59:59.

Eg. WHERE DateCreated < '20111201 00:00:00'

like image 28
ysrb Avatar answered Sep 20 '22 07:09

ysrb