views:

351

answers:

2

I know how to get in SQL (SQL Server) the current date, but with the beginning of the day:

select dateadd(DAY, datediff(day, 0, getdate()),0) 
(result:2009-09-17 00:00:00.000)

I need to get (in SQL) the current date with the beginning of this hour. For example: 2009-09-17 17:00:00 (I don't care about the exact format)

and I need to get the current date but with the beginning of this month: For example: 2009-09-01 00:00:00.000 (I don't care about the exact format)

Can you help me? Thanks in advance

+2  A: 

Try this

select DATEADD(hh,17,dateadd(DAY, datediff(day, 0, getdate()),0))

SELECT CAST('01 ' + CAST(DATENAME(MM, getdate()) AS VARCHAR(15)) + CAST(DATEPART(yyyy, GETDATE()) AS VARCHAR(5)) AS DATETIME)
astander
first: thanks. second: you explicitly put the time now (17 in your first query, 01 in your second query) . I dont want to put this numbers I need the current hour. the current month.
Hagai
Change the 17 to DATEPART(hh, GETDATE()) which gets you the current hourand the 01 is for start of month, did i misunderstand?
astander
you are the man
Hagai
+6  A: 

Just adapt your current start of day code!

All you want is start of month, start of hour. Its just the same...

select dateadd(month, datediff(month, 0, getdate()),0) 

select dateadd(hour, datediff(hour, 0, getdate()),0)
gbn
THANKS !!! you helped me a lot.
Hagai