Manage Learn to apply best practices and optimize your operations.

Using SQL DATEPART, GETDATE, DATENAME functions

SQL datetime functions DATEPART, GETDATE and DATENAME can retrieve the date and time or other individual parts of a value. Here's how to master these T-SQL tools.

Transact-SQL DATEPART functions allow you to retrieve the current date and time or individual parts of a datetime...

or smalldatetime value.

For example, you can extract the day, month or year from a datetime value, as well as the quarter, week, hour or even the millisecond. You can also retrieve the current date and time with GETDATE, or display the names of the days and months with DATENAME.

Retrieving the current date and time with GETDATE

One of the handiest datetime functions in T-SQL is GETDATE, which retrieves the current date and time based on the clock settings on the local system. To use GETDATE, simply call the function in your T-SQL statement without specifying any arguments, as in the following example:

SELECT GETDATE() AS [Current Date/Time]

Using GETDATE in the SELECT list retrieves the date/time value. (You must include the ending set of parentheses, even if you don't pass in any arguments.) The statement returns results similar to the following:

Current Date/Time

2008-07-29 10:45:13.327

By default, the GETDATE function returns the datetime value in the format shown here. However, you can change the format of the results with the CONVERT function. For information about CONVERT, refer to part two of this series, data conversions from date/time values to character types.

One of the handiest datetime functions in T-SQL is GETDATE.

Another T-SQL function that is just as easy to use is GETUTCDATE, which retrieves the current Coordinated Universal Time. The retrieved value is based on the clock and time zone settings of the local system. As with GETDATE, you can call GETUTCDATE within your Transact-SQL statement without including any arguments, as shown in the following example:

SELECT GETUTCDATE() AS [UTC Date/Time]

When you run this statement, you receive results similar to the following:

UTC Date/Time

2008-07-29 17:45:13.327

Notice that the time returned here is seven hours later than the time shown in the previous example. Both of these statements were run at the same time on a system configured for the Pacific time zone (during daylight saving time).

As you've seen in the last two examples, functions are included within the SELECT list. However, the functions are especially beneficial when you use them to define a default value in your table definition. For example, the following three statements create the Orders table -- including a datetime column (OrderDate). Inserting data into the table generates results similar to the following:

CREATE TABLE Orders
(
OrderID INT PRIMARY KEY IDENTITY,
Product VARCHAR(30) NOT NULL,
OrderAmt INT NOT NULL,
OrderDate DATETIME NOT NULL DEFAULT GETDATE()
)
GO
INSERT INTO Orders (Product, OrderAmt)
VALUES('Test Product', 12)
GO
SELECT * FROM Orders

The OrderDate column definition includes a DEFAULT clause that specifies GETDATE as the default value. As a result, when you insert a row into the table, the current date and time are automatically inserted into the column, as shown in the results returned by the SELECT statement:

OrderID

Product

OrderAmt

OrderDate

1

Test Product

12

2008-07-29 10:46:47.420

You can use this information as a timestamp to track when records were added, as well as to assist in auditing the data, if necessary. This is also handy for other operations that use the timestamp when retrieving data. An extract, transform and load process might reference the timestamp when determining whether to extract or update data.

Retrieving data with the YEAR, MONTH or DAY function

In some cases, you might want to retrieve the year, month or day from a datetime or smalldatetime value. One approach is to use the YEAR, MONTH or DAY function to retrieve the necessary data (as an integer). The following SELECT statement is an example:

SELECT YEAR(PostTime) AS [Year],
MONTH(PostTime) AS [Month],
DAY(PostTime) AS [Day]
FROM DatabaseLog
WHERE DatabaseLogID = 1

The SELECT clause includes three column expressions. The first one uses the YEAR function to retrieve the year from the PostTime column in the DatabaseLog table (in the AdventureWorks sample database). When you call the YEAR function, you specify the column name (or other expression) as an argument to the function. The MONTH and DAY functions work similarly. The second column expression in the SELECT clause uses the MONTH function to retrieve the month from the PostTime column, and the third expression uses DAY to retrieve the day. The following results show you the type of information that the statement returns:

Year

Month

Day

2016

10

14

Each value is extracted from the PostTime column and returned as an integer. (The value stored in the table is 2016-10-14 01:58:27.567.)

These functions are an easy way to retrieve the year, month or day, but, in some cases, you might want more control over the type of values returned, as well as the format of those values. In addition, you might want to extract the time from the date/time value. Fortunately, T-SQL supports functions that provide this capability.

Retrieving parts of a date/time value with DATEPART

Like the YEAR, MONTH and DAY functions, the DATEPART function returns an integer which represents a specific part of the date/time value. For example, the following SELECT statement returns the same results as the preceding example:

SELECT DATEPART(yy, PostTime) AS [Year],
DATEPART(mm, PostTime) AS [Month],
DATEPART(dd, PostTime) AS [Day]
FROM DatabaseLog
WHERE DatabaseLogID = 1

The first thing to note is that, when you call DATEPART, you specify two arguments. The first argument determines the date/time component to retrieve, and the second argument is the source column. For the first argument, you must use one of the supported abbreviations to specify the datetime part. The following table lists the date/time parts you can retrieve and the abbreviations you must use to retrieve them:

Date/time part

Abbreviations

year

yy, yyyy

quarter

qq, q

month

mm, m

day of year

dy, y

day

dd, d

week

wk, ww

weekday

dw

hour

hh

minute

mi, n

second

ss, s

millisecond

ms

For some datetime parts, more than one abbreviation is supported. You can use yy or yyyy as your first DATEPART argument to retrieve the year from the date/time value. Notice that the table includes abbreviations for date/time parts other than year, month or day. You can retrieve the quarter, the day of the year, the week of the year and the weekday, as shown in the following SELECT statement:

SELECT DATEPART(qq, PostTime) AS [Quarter],
DATEPART(dy, PostTime) AS [DayOfYear],
DATEPART(wk, PostTime) AS [Week],
DATEPART(dw, PostTime) AS [Weekday]
FROM DatabaseLog
WHERE DatabaseLogID = 1

As in the preceding example, each instance of DATEPART includes two arguments: the date/time part abbreviation and the source column. The statement returns the following results:

Quarter

DayOfYear

Week

Weekday

4

287

42

6

Notice that the weekday is shown as 6. By default, SQL Server begins the week with Sunday, so weekday 6 is equivalent to Friday.

The preceding two examples retrieved only values related to dates. However, as the table below shows, you can also retrieve data related to time:

SELECT DATEPART(hh, PostTime) AS [Hour],
DATEPART(mi, PostTime) AS [Minute],
DATEPART(ss, PostTime) AS [Second],
DATEPART(ms, PostTime) AS [Millisecond]
FROM DatabaseLog
WHERE DatabaseLogID = 1

This statement is retrieving the hour, minute, second and millisecond, as shown in the following results:

Hour

Minute

Second

Millisecond

1

58

27

567

Displaying names of days/months with DATENAME

The primary limitation of the DATEPART function is that it returns only integers, which is why Friday is shown as 6. However, if you want to display actual names of days and months, you can use the DATENAME function.

The DATENAME function works exactly like the DATEPART function. DATENAME takes the same number of arguments and supports the same abbreviations. For example, if you want to retrieve the year, month and day, as you saw in an earlier example, you simply replace DATEPART with DATENAME, as shown in the following statement:

SELECT DATENAME(yy, PostTime) AS [Year],
DATENAME(mm, PostTime) AS [Month],
DATENAME(dd, PostTime) AS [Day]
FROM DatabaseLog
WHERE DatabaseLogID = 1

Now, your results will look like the following:

Year

Month

Day

2005

October

14

The month value is now October, rather than 10. The year and day, however, remain integers because that's the only way to represent them. You can also use the DATENAME function for other date/time components, as in the following example:

SELECT DATENAME(qq, PostTime) AS [Quarter],
DATENAME(dy, PostTime) AS [DayOfYear],
DATENAME(wk, PostTime) AS [Week],
DATENAME(dw, PostTime) AS [Weekday]
FROM DatabaseLog
WHERE DatabaseLogID = 1

Once again, I've replaced DATEPART with DATENAME, but changed nothing else. The statement returns the following results:

Quarter

DayOfYear

Week

Weekday

4

287

42

Friday

Notice that the quarter, day of the year and week are integers, but the weekday says Friday, rather than 6. You can also use DATENAME to retrieve the time components of a date/time value, but the results will always be integers, as you would expect.

You can use any of these functions individually or in conjunction with each other to concentrate values. Experiment with these functions to gain a clear sense of how each one works. 

Next Steps

Basics with datetime and smalldatetime

Converting date/time values to character types

Calculating datetime values

New datetime data types

This was last published in April 2017

Dig Deeper on SQL-Transact SQL (T-SQL)

Join the conversation

1 comment

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

Which datetime functions do you use most?
Cancel

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close