Assigment 12
Assigment 12
Explain all date functions along with the syntax and an example.
1. CURDATE() / CURRENT_DATE()
Description: Returns the current date.
Syntax- CURDATE() | CURRENT_DATE
Example: SELECT CURDATE(); -- Output: '2024-11-05'
2. NOW()
Description: Returns the current date and time.
Syntax: NOW()
Example: SELECT NOW(); -- Output: '2024-11-05 12:34:56'
3. DATE()
Description: Extracts the date part from a date or datetime expression.
Syntax: DATE(expression)
Example: SELECT DATE(NOW()); -- Output: '2024-11-05'
4. DATEDIFF()
Description: Returns the number of days between two date values.
Syntax: DATEDIFF(date1, date2)
Example: SELECT DATEDIFF('2024-11-05', '2024-10-01'); -- Output: 35
5. DATE_ADD()
Description: Adds a time interval to a date.
Syntax: DATE_ADD(date, INTERVAL value unit)
Example: SELECT DATE_ADD('2024-11-05', INTERVAL 10 DAY); -- Output: '2024-11-
15'
6. DATE_SUB()
Description: Subtracts a time interval from a date.
Syntax: DATE_SUB(date, INTERVAL value unit)
Example: SELECT DATE_SUB('2024-11-05', INTERVAL 10 DAY); -- Output: '2024-10-
26'
7. YEAR()
Description: Extracts the year from a date.
Syntax: YEAR(date)
Example: SELECT YEAR('2024-11-05'); -- Output: 2024
8. MONTH()
Description: Extracts the month from a date.
Syntax: MONTH(date)
Example: SELECT MONTH('2024-11-05'); -- Output: 11
9. DAY()
Description: Extracts the day of the month from a date.
Syntax: DAY(date)
Example: SELECT DAY('2024-11-05'); -- Output: 5
10. STR_TO_DATE()
Description: Converts a string into a date based on the specified format.
Syntax: STR_TO_DATE(string, format)
Example: SELECT STR_TO_DATE('05/11/2024', '%d/%m/%Y'); -- Output: '2024-11-05'
11. FORMAT()
Description: Formats a date according to the specified format.
Syntax: FORMAT(date, format)
Example: SELECT DATE_FORMAT('2024-11-05', '%W, %M %d, %Y'); -- Output:
'Tuesday, November 05, 2024'
12. EXTRACT()
Description: Retrieves subparts (like year, month, day) from a date.
Syntax: EXTRACT(unit FROM date)
Example: SELECT EXTRACT(YEAR FROM '2024-11-05'); -- Output: 2024
13. LAST_DAY()
Description: Returns the last day of the month for a given date.
Syntax: LAST_DAY(date)
Example: SELECT LAST_DAY('2024-11-05'); -- Output: '2024-11-30'
14. TIMESTAMPDIFF()
Description: Returns the difference between two timestamps.
Syntax: TIMESTAMPDIFF(unit, datetime1, datetime2)
Example: SELECT TIMESTAMPDIFF(DAY, '2024-10-01', '2024-11-05'); -- Output: 35
15. TIMESTAMP()
Description: Returns a datetime value based on a date or datetime expression.
Syntax: TIMESTAMP(date)
Example: SELECT TIMESTAMP('2024-11-05 12:34:56'); -- Output: '2024-11-05
12:34:56'