SQL provides a variety of date and time functions that allow you to manipulate and retrieve date-related information efficiently. These functions are useful for handling timestamps, date calculations, and formatting.
Common Date and Time Functions
- GETDATE(): Returns the current system date and time.
- SYSDATETIME(): Returns the current system date and time with more precision.
- DATEADD(): Adds a specified time interval to a date.
- DATEDIFF(): Returns the difference between two dates.
- FORMAT(): Formats a date value into a specified format.
- EOMONTH(): Returns the last day of the month for a given date.
- CONVERT(): Converts a date to a different format or datatype.
- CAST(): Converts a date or time value to another datatype.
Example Usage of Date and Time Functions
1. Using GETDATE() Function
SELECT GETDATE() AS CurrentDateTime;
Output. 2024-03-19 14:30:00.000 (Example output, actual output may vary)
2. Using DATEADD() Function
SELECT DATEADD(DAY, 7, '2024-03-19') AS NewDate;
Output. 2024-03-26
3. Using DATEDIFF() Function
SELECT DATEDIFF(DAY, '2024-03-01', '2024-03-19') AS DaysDifference;
Output.18
4. Using FORMAT() Function
SELECT Format(Getdate(), 'yyyy-MM-dd') AS FormattedDate;
SELECT Format(Getdate(), 'dd/MM/yyyy') AS FormattedDateDDMMYYYY;
SELECT Format(Getdate(), 'MMMM dd, yyyy') AS FormattedDateLong;
Output
FormattedDate |
FormattedDateDDMMYYYY |
FormattedDateLong |
2024-03-19 |
19/03/2024 |
March 19, 2024 |
5. Using EOMONTH() Function
SELECT EOMONTH(GETDATE()) AS EndOfMonth;
Output. 2024-03-31
6. Using CONVERT() Function
SELECT CONVERT(VARCHAR, Getdate(), 101) AS MMDDYYYY;
SELECT CONVERT(VARCHAR, Getdate(), 103) AS DDMMYYYY;
SELECT CONVERT(VARCHAR, Getdate(), 120) AS YYYYMMDD_HHMMSS;
Output
MMDDYYYY |
DDMMYYYY |
YYYYMMDD_HHMMSS |
03/19/2024 |
19/03/2024 |
2024-03-19 14:30:00 |
7. Using CAST() Function
SELECT CAST(GETDATE() AS DATE) AS OnlyDate;
SELECT CAST(GETDATE() AS TIME) AS OnlyTime;
Output
OnlyDate |
OnlyTime |
2024-03-19 |
14:30:00 |
When to Use Date and Time Functions?
- Scheduling and Deadlines: Useful for calculating due dates, expiration dates, and reminders.
- Historical Data Analysis: Helps in analyzing trends and past performance based on timestamps.
- Log Management: Essential for tracking events, user activity, and system logs.
- Data Formatting: Used to present dates in user-friendly formats in reports and applications.
Advantages of Date and Time Functions
- Simplifies date calculations and manipulations.
- Enhances data consistency and accuracy.
- Improves query performance by utilizing built-in SQL functions.
Date and time functions are an essential part of SQL, providing efficient ways to handle date-related operations.