2081 9

BIT301 ยท 2081 ยท 5 marks

Describe the date time functions with examples.

Describe the date time functions with examples. [5]

Web Technology II

Quick answer

Date and time functions are built-in SQL functions used to perform operations on date and time values such as retrieving the current date/time, extracting parts of a date, and performing date arithmetic.

Date and Time Functions in SQL

Note: The reference notes did not contain this topic, so the answer is based on standard SQL/database curriculum covered in TU BSc CSIT.


Date and Time Functions


Commonly Used Date and Time Functions

1. NOW()

Returns the current date and time.

SELECT NOW();
-- Output: 2024-05-15 10:30:45

2. CURDATE() / CURRENT_DATE()

Returns the current date (without time).

SELECT CURDATE();
-- Output: 2024-05-15

3. CURTIME() / CURRENT_TIME()

Returns the current time (without date).

SELECT CURTIME();
-- Output: 10:30:45

4. DATE()

Extracts only the date part from a datetime expression.

SELECT DATE('2024-05-15 10:30:45');
-- Output: 2024-05-15

5. YEAR(), MONTH(), DAY()

Extracts the year, month, or day from a date.

SELECT YEAR('2024-05-15');   -- Output: 2024
SELECT MONTH('2024-05-15');  -- Output: 5
SELECT DAY('2024-05-15');    -- Output: 15

6. DATEDIFF()

Returns the difference in days between two dates.

SELECT DATEDIFF('2024-05-15', '2024-01-01');
-- Output: 135

7. DATE_ADD() and DATE_SUB()

Adds or subtracts a time interval from a date.

SELECT DATE_ADD('2024-05-15', INTERVAL 10 DAY);
-- Output: 2024-05-25

SELECT DATE_SUB('2024-05-15', INTERVAL 1 MONTH);
-- Output: 2024-04-15

8. DATE_FORMAT()

Formats a date value according to a specified format.

SELECT DATE_FORMAT('2024-05-15', '%d/%m/%Y');
-- Output: 15/05/2024

Summary Table

FunctionPurpose
NOW()Current date and time
CURDATE()Current date only
CURTIME()Current time only
DATEDIFF()Difference between two dates
DATE_ADD()Add interval to a date
DATE_FORMAT()Format a date value

These functions are widely used in database applications for tasks like calculating age, finding records within a date range, and formatting date output for reports.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.