Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql - beginning of hour, month etc

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

like image 211
Hagai L Avatar asked Sep 17 '09 14:09

Hagai L


People also ask

How do I get the beginning of the month in SQL?

Here's how this works: First we format the date in YYYYMMDD... format truncating to keep just the 6 leftmost characters in order to keep just the YYYYMM portion, and then append '01' as the month - and voila! you have the first day of the current month.

How do I get the start of the hour in SQL?

HOUR part of the DateTime in Sql Server We can use DATEPART() function to get the HOUR part of the DateTime in Sql Server, here we need to specify datepart parameter of the DATEPART function as hour or hh.

How do I get the current month start and end in SQL?

Below are the functions with logic explanation: 1. First day of current month: select DATEADD(mm, DATEDIFF(m,0,GETDATE()),0): in this we have taken out the difference between the months from 0 to current date and then add the difference in 0 this will return the first day of current month.

How do I get the start of the day in SQL?

SQL Server DAY() Function The DAY() function returns the day of the month (from 1 to 31) for a specified date.


Video Answer


1 Answers

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) 
like image 156
gbn Avatar answered Oct 05 '22 04:10

gbn