← Back to Chapters

MySQL Time Functions

⏰ MySQL Time Functions

? Quick Overview

MySQL time functions help manipulate, retrieve, compare, and format time-based values. They are essential for applications that track schedules, logs, durations, and real-time events.

? Key Concepts

  • Extracting parts of a time value
  • Adding or subtracting time intervals
  • Calculating time differences
  • Formatting time output

? Syntax & Theory

Time functions in MySQL operate on TIME and DATETIME values. They return results in standard formats that can be further processed or formatted.

? Code Examples

? View Code Example
// Get current server time
SELECT CURTIME() AS current_time;
? View Code Example
// Get current date and time
SELECT NOW() AS current_datetime;
? View Code Example
// Extract time from datetime
SELECT TIME('2025-07-18 14:23:45') AS extracted_time;
? View Code Example
// Add 2 hours to a time value
SELECT DATE_ADD('14:23:45', INTERVAL 2 HOUR) AS new_time;
? View Code Example
// Subtract 30 minutes from a time
SELECT DATE_SUB('14:23:45', INTERVAL 30 MINUTE) AS new_time;
? View Code Example
// Calculate difference between two times
SELECT TIMEDIFF('16:23:45','14:23:45') AS time_difference;
? View Code Example
// Convert seconds into time format
SELECT SEC_TO_TIME(3600) AS time_format;
? View Code Example
// Format time into HH:MM:SS
SELECT TIME_FORMAT('14:23:45','%H:%i:%s') AS formatted_time;

? Live Output / Explanation

Each query returns a computed time value based on the function used. These outputs are commonly used in reports, dashboards, and scheduling logic.

? Use Cases

  • Tracking login and logout durations
  • Scheduling reminders and alerts
  • Calculating time-based analytics
  • Formatting time for UI display

✅ Tips & Best Practices

  • Use TIME_FORMAT() to customize time output
  • Combine DATE_ADD() with CURTIME() for dynamic calculations
  • Store time consistently to avoid conversion issues

? Try It Yourself

  • Add 45 minutes to the current time
  • Find the difference between two custom times
  • Convert 7265 seconds into HH:MM:SS format