SQL Datetime Functions: Usage Guide

The datetime function in SQL is used to manipulate date and time data. It can be used to retrieve the current date and time, as well as perform various date and time operations.

Here are some common datetime functions and their usage:

  1. Obtain the current date and time using CURRENT_TIMESTAMP/GETDATE().
    For example: SELECT CURRENT_TIMESTAMP; or SELECT GETDATE();
  2. DATEADD(): Add a certain time interval to a date or time value.
    For example: SELECT DATEADD(MINUTE, 30, ‘2022-01-01 12:00:00’); // Add 30 minutes to the specified date and time.
  3. DATEDIFF() function calculates the time interval between two dates.
    For example: SELECT DATEDIFF(DAY, ‘2022-01-01’, ‘2022-01-10’); // Calculate the difference in days between two dates.
  4. DATEPART(): Extract a specific part of a date or time.
    For example: SELECT DATEPART(YEAR, ‘2022-01-01’); // Extracts the year
  5. Convert function: converts one data type to another data type.
    For example: SELECT CONVERT(VARCHAR, GETDATE(), 120); // converts current date and time to a string in a specified format.

These are just a few examples of datetime functions, SQL offers many other date and time functions that can be used to handle and manipulate date and time data as needed.

bannerAds