The TIMESTAMP() function in MySQL is used to return a datetime value based on a specified date (and optionally a time) value.
Definition and Usage
- Purpose: The function combines a date (or datetime) value with an optional time value to return a complete datetime value. If only a date is provided, it returns that date with the default time of
00:00:00. - Syntax:
TIMESTAMP(expression, time)
Syntax
TIMESTAMP(expression, time)
- expression: A required date or datetime value.
- time: An optional time value to add to the
expression. If provided, the time value will be combined with the date value to create a complete datetime.
Technical Details
- Works in: From MySQL 4.0 onwards.
- Return Type: Returns a
DATETIMEvalue, combining both the date and time components. - Behavior:
- If only the date (
expression) is provided, the function returns that date with the default time00:00:00. - If both the date and time are provided, it returns a
DATETIMEvalue by combining the two.
- If only the date (
Examples
Example 1: Return a datetime value by combining date and time
SELECT TIMESTAMP("2017-07-23", "13:10:11");
Result:
2017-07-23 13:10:11
Explanation: The date 2017-07-23 is combined with the time 13:10:11 to return a complete datetime value.
Example 2: Return a datetime value based on only a date
SELECT TIMESTAMP("2017-07-23");
Result:
2017-07-23 00:00:00
Explanation: Since no time is provided, the function returns the date 2017-07-23 with the default time 00:00:00.
Use Cases
- Creating Complete Datetime: When you have a date value and want to combine it with a specific time (e.g., event start date with time).
- Data Formatting: Useful for formatting and combining date and time values for consistent output in reports and databases.
- Default Time Handling: When you want to assign a default time (
00:00:00) to a date in cases where only the date is provided.
Key Notes
- The
TIMESTAMP()function is different from theCURRENT_TIMESTAMPfunction, which returns the current date and time of the server. - This function will not adjust time zones; the result will be based on the system's current time zone unless explicitly handled.