Tag Archives: getdate

How to get the date difference, current date, only year, day month in SQL Server

How to get the current date  in SQL Server

List of commonly used data and time functions:
GETDATE()
DATEADD()
DATEPART()
DATEDIFF()
DATENAME()
DAY()
MONTH()
YEAR()

How to get the current data in SQL Server

GETDATE()
GETDATE() is very common used method which returns exact date time from the system. It does not used any parameter. Lets see as follows:

select getdate()

2025-12-09 16:02:22.597

How to add and subtract datatime in SQL Server

DATEADD()
DATEADD() is used to add or subtract datetime. Its return a new datetime based on the added or subtracted interval.

Declare @Date datetime 

set @Date = (SELECT GETDATE());
print  @Date -- Print Current Date
-- Adding 5 days with Current Date
SELECT DATEADD(day, 5,@Date ) AS NewTime
-----------------------------------------------------
Aug 15 2009  9:19PM
NewTime
-----------------------
2009-08-20 21:19:15.170

How to get the part like year, month and hour from the date in SQL Server

DATEPART()
Datepart is used when we need a part of date or time from a datetime variable. We can use DATEPART() method only with select command.

DATEPART(datepart, date)

SELECT DATEPART(year, GETDATE()) AS 'Year'
-- Get Only Month
SELECT DATEPART(month, GETDATE()) AS 'Month'
-- Get Only hour
SELECT DATEPART(hour, GETDATE()) AS 'Hour

How to do the difference between two data time

DATEDIFF()
Datediff is a function to find out the difference between two DateTime elements.

DATEDIFF (datepart, startdate, enddate)


SELECT DATEDIFF(day, '2023-01-01', '2023-01-10') AS DateDiff;

Datediff
--------
9

SELECT DATEDIFF(year, '2017/08/25', '2021/08/25') AS DateDiff;

SELECT DATEDIFF(month, '2017/08/25', '2021/08/25') AS DateDiff;

SELECT DATEDIFF(hour, '2023-01-01 07:00', '2023-01-01 12:45') AS

Datepart Values: Valid datepart values include year (yy), month (mm), day (dd), hour (hh), minute (mi), second (ss), etc

How to get the name of date time in SQL Server

DATENAME()
DATENAME() is a function to find out the date name from the datetime value.

SELECT DATENAME(yy, '2017/08/25') AS YEARDD;

YEARDD
-------
2017 

year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond