If you are a SQL Server enthusiast, you might have come across various date and time functions that can be used to manipulate and retrieve date and time values in your queries. In this article, we will explore some common date and time functions in SQL Server and understand how they can be used.
1. GETDATE()
The GETDATE() function is used to retrieve the current date and time from the SQL Server. It returns a datetime value.
Example:
SELECT GETDATE() AS CurrentDateTime;
This will return the current date and time in the format ‘YYYY-MM-DD HH:MI:SS’.
2. DATEADD()
The DATEADD() function is used to add or subtract a specified time interval (such as days, months, or years) to a given date.
Example:
SELECT DATEADD(MONTH, 1, GETDATE()) AS NextMonth;
This will return the date that is one month ahead of the current date.
3. DATEDIFF()
The DATEDIFF() function is used to calculate the difference between two dates. It returns the number of specified date parts (such as days, months, or years) between the two dates.
Example:
SELECT DATEDIFF(DAY, '2021-01-01', '2021-01-31') AS DaysDifference;
This will return the number of days between January 1, 2021, and January 31, 2021.
4. DATEPART()
The DATEPART() function is used to extract a specific part (such as year, month, or day) from a given date.
Example:
SELECT DATEPART(YEAR, '2021-01-01') AS Year;
This will return the year part of the given date.
5. CONVERT()
The CONVERT() function is used to convert a value from one data type to another. It can also be used to format date and time values.
Example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS FormattedDate;
This will return the current date in the format ‘MM/DD/YYYY’.
These are just a few examples of the date and time functions available in SQL Server. By using these functions effectively, you can perform various operations on date and time values in your SQL queries.