20.2. SQL Part 2 - Date and Time Functions¶
20.2.1. Date and Time Data Types and Functions¶
Function |
Definition |
Syntax |
Value Returned |
---|---|---|---|
Returns a timestamp that includes the date and time of the server. |
|
2022-01-04 22:12:25.567 |
|
Returns a timestamp that includes the date and time of the server. |
|
2022-01-04 22:12:25.5675908 |
|
Adds a time period to a date. In this example, we are increasing the month value from |
|
2022-03-24 00:00:00.000 |
|
Calculates and returns the difference of a date part between an end date and a start date. |
|
29 |
|
Can also be used to compare months. |
|
1 |
|
Can also compare years. |
|
38 |
|
Returns a string representing the desired date part. |
|
25 |
|
|
July |
||
|
2022 |
||
Returns an integer representing the desired date part. |
|
21 |
|
|
08 |
||
|
2022 |
||
Each part of a date. |
|
21 |
|
|
8 |
||
|
2022 |
||
Paired with |
|
Jan 5 2022 7:25PM |
|
These examples convert the server date into various formats. The first example is the default format, the second example is format number 7. |
|
Jan 05, 22 |
|
Used to set the format or reformat dates. This example is using the following date information: |
|
05/01/2022 |
|
The second example requests only the time in hours and minutes. Note that |
|
07:38 |
20.2.1.1. Check Your Understanding¶
Question
Willow has a column in her table containing dates the library branches opened. She wants to compare them to today’s date. Which function would allow her to do that?
DATEADD
MONTH
CONVERT
DATEDIFF
Question
Willow has a table that contains dates library books are checked out. She uses the following function in her query: WHERE DATEPART(MONTH, BorrowDate) = 05
. What will this return?
Rows of data where books were borrowed in the month of May
Rows of data where books were borrowed on the 5th day of the month.
Rows of data where books were borrowed in 2005.
Rows of data where the same library user borrowed exactly 5 books.
Question
Willow wants to have all the dates in her database in the same format of month-day-year
. She used the following syntax: FORMAT(ModifiedDate, 'mm/dd/yyyy')
and received an error message. Why?