Complete Guide: Get, Format, and Use Current Time in MySQL

目次

1. Introduction

The Importance of Handling the Current Time in MySQL

MySQL places great importance on handling time in order to properly manage the information stored in a database. In particular, functions that retrieve and manipulate the current time are used in many scenarios, such as logging, schedule management, and recording data update timestamps. For example, you can leverage the current time in cases such as the following.
  • Order management system: automatically record order timestamps
  • Log management: record system error logs and access logs
  • Scheduling feature: store future appointments in the database and send reminders
Thus, handling the current time correctly in MySQL is crucial for improving data integrity and analytical accuracy.

What users who want to know “MySQL current time” are looking for

Many users who search for “MySQL current time” have the following objectives.
  1. Want to retrieve the current time
  2. Want to format the retrieved time
  3. Want to manipulate the time (add/subtract)
  4. Want to query data within a specific time range
  5. Want to handle time with time zone considerations
To meet these needs, this article provides a detailed explanation, from basics to advanced topics, of how to retrieve the current time in MySQL.

What you’ll learn in this article

In this article, you can systematically learn the following points.
  • Basic methods for retrieving the current time in MySQL
  • How to change the format of the current time
  • How to perform date/time calculations (addition/subtraction)
  • How to handle time with time zone considerations
  • Practical use cases (log management, schedule management, etc.)
By leveraging this information, you can manage MySQL data more efficiently.

2. How to Get the Current Time in MySQL

Main Methods to Get the Current Time in MySQL

There are several ways to retrieve the current time in MySQL. Primarily, you use the NOW() function, but depending on the use case, you can also use CURRENT_TIMESTAMP, CURDATE(), or CURTIME().

NOW() to Retrieve the Current Time

Basic Syntax of NOW()

SELECT NOW();

Result (Example)

2025-02-01 15:30:45
NOW() retrieves the current date and time in the YYYY-MM-DD HH:MM:SS format.

Using CURRENT_TIMESTAMP

CURRENT_TIMESTAMP also returns the result as NOW().

Basic Syntax of CURRENT_TIMESTAMP

SELECT CURRENT_TIMESTAMP;

Result (Example)

2025-02-01 15:30:45
CURRENT_TIMESTAMP can be used as a column default value.

Example of Setting CURRENT_TIMESTAMP as a Default Value

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_time DATETIME DEFAULT CURRENT_TIMESTAMP
);

Getting Only the Date with CURDATE()

Basic Syntax of CURDATE()

SELECT CURDATE();

Result (Example)

2025-02-01
You can obtain just the date without the time.

Getting Only the Time with CURTIME()

Basic Syntax of CURTIME()

SELECT CURTIME();

Result (Example)

15:30:45
CURTIME() is used when you need to retrieve only the time.

Comparison Table of Functions

FunctionData RetrievedTypical Use
NOW()Current date and time (YYYY-MM-DD HH:MM:SS)Recording creation/update timestamps of data
CURRENT_TIMESTAMPSame as NOW() (can be applied as a column default value)Default value when creating a table
CURDATE()Current date only (YYYY-MM-DD)Getting today’s date / filtering
CURTIME()Current time only (HH:MM:SS)Extracting data for specific time ranges

Summary

  • If you need the current date and time, use NOW()
  • For column default values, use CURRENT_TIMESTAMP
  • If you only want the date, use CURDATE()
  • If you only want the time, use CURTIME()

3. How to format the current time in MySQL

Using DATE_FORMAT() to format the current time

Basic syntax of DATE_FORMAT()

SELECT DATE_FORMAT(NOW(), 'format_string');
By specifying a format_string, you can change the display format of date and time.

Basic format examples

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s');
Result (example)
2025-02-01 15:30:45

List of format options for DATE_FORMAT()

SymbolDescriptionExample (2025-02-01 15:30:45)
%YYear (4 digits)2025
%mMonth (zero-padded)02
%dDay (zero-padded)01
%HHour (24-hour)15
%hHour (12-hour)03
%iMinute (zero-padded)30
%sSecond (zero-padded)45
%pAM/PMPM

Concrete examples using DATE_FORMAT()

Japanese format

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i');
Result
2025-02-01 15:30

12-hour format (with AM/PM)

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %h:%i:%s %p');
Result
2025-02-01 03:30:45 PM

Formatting time using TIME_FORMAT()

TIME_FORMAT() is a formatting function specialized for time data (TIME type).

Basic syntax of TIME_FORMAT()

SELECT TIME_FORMAT(NOW(), '%H:%i:%s');
Result
15:30:45

Converting a string to a date using STR_TO_DATE()

Use STR_TO_DATE() when converting a string date/time to MySQL’s DATETIME type.

Basic syntax of STR_TO_DATE()

SELECT STR_TO_DATE('2025-2-1 15:30', '%Y-%c-%e %H:%i');
Result
2025-02-01 15:30:00

Summary

  • Use DATE_FORMAT() to change date/time formatting
  • TIME_FORMAT() can also be used for time-only formatting
  • You can combine format options to freely change the display format
  • Using STR_TO_DATE(), you can also convert strings to date types

4. Date and Time Calculations Using MySQL’s Current Timestamp

Using DATE_ADD() to Get Future Dates

Basic Syntax of DATE_ADD()

SELECT DATE_ADD(NOW(), INTERVAL numeric_value time_unit);
Time UnitMeaningExample
SECONDSecondDATE_ADD(NOW(), INTERVAL 30 SECOND)
MINUTEMinuteDATE_ADD(NOW(), INTERVAL 10 MINUTE)
HOURHourDATE_ADD(NOW(), INTERVAL 2 HOUR)
DAYDayDATE_ADD(NOW(), INTERVAL 7 DAY)
MONTHMonthDATE_ADD(NOW(), INTERVAL 3 MONTH)

Get Date and Time 7 Days Later

SELECT DATE_ADD(NOW(), INTERVAL 7 DAY);
Sample Output
2025-02-08 14:00:00

Using DATE_SUB() to Get Past Dates

Basic Syntax of DATE_SUB()

SELECT DATE_SUB(NOW(), INTERVAL numeric_value time_unit);

Get Date 30 Days Ago

SELECT DATE_SUB(NOW(), INTERVAL 30 DAY);
Sample Output
2025-01-02 14:00:00

Using TIMESTAMPDIFF() to Find the Difference Between Two DateTimes

Basic Syntax of TIMESTAMPDIFF()

SELECT TIMESTAMPDIFF(unit, datetime1, datetime2);
UnitValues Obtained
SECONDDifference in seconds
MINUTEDifference in minutes
HOURDifference in hours
DAYDifference in days
MONTHDifference in months

Calculate Difference Between Two Dates in Days

SELECT TIMESTAMPDIFF(DAY, '2025-01-01', NOW());
Sample Output
31

Using DATEDIFF() to Calculate Day Difference

SELECT DATEDIFF('2025-02-10', '2025-02-01');
Sample Output
9

Using TIME_TO_SEC() to Convert Time to Seconds

SELECT TIME_TO_SEC('01:30:00');
Output
5400

Using SEC_TO_TIME() to Convert Seconds to Time

SELECT SEC_TO_TIME(5400);
Output
01:30:00

Summary

FunctionPurposeExample
DATE_ADD()Retrieve future date and timeSELECT DATE_ADD(NOW(), INTERVAL 7 DAY);
DATE_SUB()Retrieve past date and timeSELECT DATE_SUB(NOW(), INTERVAL 30 DAY);
TIMESTAMPDIFF()Get difference between two datesSELECT TIMESTAMPDIFF(DAY, '2025-01-01', NOW());
DATEDIFF()Get difference between two dates in daysSELECT DATEDIFF('2025-02-10', '2025-02-01');
TIME_TO_SEC()Convert time to secondsSELECT TIME_TO_SEC('01:30:00');
SEC_TO_TIME()Convert seconds to timeSELECT SEC_TO_TIME(5400);

5. Time Zone Settings and Their Impact on the Current Time

Checking MySQL’s Current Time Zone

Checking the System-Wide Default Time Zone

SHOW VARIABLES LIKE '%time_zone%';
Example output
+-----------------+--------+
| Variable_name   | Value  |
+-----------------+--------+
| system_time_zone | UTC    |
| time_zone       | +00:00 |
+-----------------+--------+

Changing MySQL’s Time Zone

Changing the Time Zone per Session

SET SESSION time_zone = 'Asia/Tokyo';

Changing the Server-Wide Time Zone (set in my.cnf)

[mysqld]
default-time-zone = '+09:00'

Restart MySQL After Changing Settings

sudo systemctl restart mysql

How to Retrieve UTC Time

SELECT UTC_TIMESTAMP();
Example output
2025-02-01 14:30:45

Convert to a Different Time Zone with CONVERT_TZ()

SELECT CONVERT_TZ(NOW(), 'Asia/Tokyo', 'UTC');
Output
2025-02-01 14:30:45

Setting Different Time Zones per User

Convert to the User’s Time Zone

SELECT CONVERT_TZ(NOW(), 'UTC', 'America/New_York');
Example output
2025-02-01 09:30:45

The Difference Between TIMESTAMP and DATETIME Types

Data TypeTime Zone EffectExample
TIMESTAMPAffected (converted to UTC)Stored after conversion to UTC
DATETIMEUnaffected (fixed value)Remains as YYYY-MM-DD HH:MM:SS

Example of Data Storage for TIMESTAMP and DATETIME

CREATE TABLE time_test (
    ts_column TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    dt_column DATETIME DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO time_test () VALUES ();
SELECT * FROM time_test;
Example output
+---------------------+---------------------+
| ts_column          | dt_column           |
+---------------------+---------------------+
| 2025-02-01 14:30:45 | 2025-02-01 23:30:45 |
+---------------------+---------------------+

Summary

  • Check the current time zoneSHOW VARIABLES LIKE '%time_zone%';
  • Change per sessionSET SESSION time_zone = 'Asia/Tokyo';
  • Change the server-wide default → Set default-time-zone = '+09:00' in my.cnf
  • Retrieve UTC timeSELECT UTC_TIMESTAMP();
  • Time zone conversionSELECT CONVERT_TZ(NOW(), 'UTC', 'Asia/Tokyo');
  • TIMESTAMP is affected by time zones, while DATETIME is fixed

6. Practical Use Cases (How to Use MySQL’s Current Time in Real-World Situations)

Log Management (Recording Data Creation and Update Timestamps)

Create Table (Including Creation and Update Timestamps)

CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Insert Data

INSERT INTO logs (event) VALUES ('User logged in');

Update Data

UPDATE logs SET event = 'User changed password' WHERE id = 1;

Schedule Management (Automatic Future Date Calculation)

Schedule an Event One Week Later

INSERT INTO schedule (event_name, event_date) 
VALUES ('Project deadline', DATE_ADD(NOW(), INTERVAL 7 DAY));

Extract Data for a Specific Period

Get This Month’s Data

SELECT * FROM orders 
WHERE order_date BETWEEN DATE_FORMAT(CURDATE(), '%Y-%m-01') AND LAST_DAY(CURDATE());

Access History Recording

Table for Recording Access Logs

CREATE TABLE access_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    access_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Record User Access

INSERT INTO access_logs (user_id) VALUES (123);

Managing Data Expiration

Delete Data Older Than 30 Days

DELETE FROM logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY);

Summary

Use CaseFunction UsedExample
Log ManagementCURRENT_TIMESTAMPcreated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
Schedule ManagementDATE_ADD()INSERT INTO schedule VALUES (DATE_ADD(NOW(), INTERVAL 7 DAY));
Specific Period Data RetrievalBETWEEN, CURDATE()SELECT * FROM orders WHERE order_date BETWEEN DATE_FORMAT(CURDATE(), '%Y-%m-01') AND LAST_DAY(CURDATE());
Access History RecordingTIMESTAMPINSERT INTO access_logs (user_id) VALUES (123);
Old Data DeletionDATE_SUB()DELETE FROM logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY);

7. Common Errors and Troubleshooting

NOW() cannot be retrieved in the correct time zone

Cause

  • MySQL’s default time zone is set to UTC
  • Session-specific time zone settings are incorrect

Solution

Check the current time zone
SHOW VARIABLES LIKE '%time_zone%';
Temporarily change the time zone
SET SESSION time_zone = 'Asia/Tokyo';
Change the server-wide default time zone
[mysqld]
default-time-zone = '+09:00'
Restart MySQL for the changes to take effect.

CURRENT_TIMESTAMP returns an unexpected date/time

Cause

  • Using a TIMESTAMP column (subject to time zone effects)
  • Server time zone is set to UTC

Solution

Using DATETIME type avoids time zone effects
CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
If using TIMESTAMP type, convert with CONVERT_TZ()
SELECT CONVERT_TZ(event_time, 'UTC', 'Asia/Tokyo') FROM logs;

Results of TIMESTAMPDIFF() differ from expectations

Cause

  • TIMESTAMPDIFF() rounds calculations per unit
  • Example: TIMESTAMPDIFF(DAY, '2025-02-01 23:59:59', '2025-02-02 00:00:01')0 days

Solution

  • Perform more accurate calculations in seconds
SELECT TIMESTAMPDIFF(SECOND, '2025-02-01 23:59:59', '2025-02-02 00:00:01');
Result
2

Choosing between TIMESTAMP and DATETIME

Data TypeTime Zone EffectRecommended Use
TIMESTAMPAffected (converted to UTC)Systems used by worldwide users
DATETIMEUnaffected (fixed value)Strictly managing local time
When using TIMESTAMP
CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
When using DATETIME
CREATE TABLE reservations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    reserved_at DATETIME NOT NULL
);

Summary

ErrorCauseSolution
NOW() time is offServer time zone setting differsSET SESSION time_zone = 'Asia/Tokyo';
CURRENT_TIMESTAMP returns unexpected date/timeEffect of TIMESTAMP typeUse DATETIME type
Result of TIMESTAMPDIFF() differs from expectationsRounding error impactUse TIMESTAMPDIFF(SECOND, datetime1, datetime2)
Don’t understand the difference between TIMESTAMP and DATETIMEWhether time zone affects themTIMESTAMP is converted to UTC, but DATETIME is fixed
When handling MySQL’s current time, understanding configuration and data type characteristics helps prevent unexpected errors.

8. FAQ (Frequently Asked Questions and Answers)

What is the difference between NOW() and CURRENT_TIMESTAMP?

Answer

In general, both have the same functionality, but only CURRENT_TIMESTAMP can be used when setting a column’s default value.
CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

How to retrieve the current time in UTC with MySQL?

Answer

Using the following query, you can retrieve the current UTC time regardless of MySQL’s timezone settings.
SELECT UTC_TIMESTAMP();
Also, if you want to convert the result of NOW() to UTC, use CONVERT_TZ().
SELECT CONVERT_TZ(NOW(), 'Asia/Tokyo', 'UTC');

Should date and time be stored in separate columns?

Answer

  • Want to store date and time together (logs, reservation management)
  CREATE TABLE reservations (
      id INT AUTO_INCREMENT PRIMARY KEY,
      reserved_at DATETIME NOT NULL
  );
  • Want to manage date and time separately (timesheets, etc.)
  CREATE TABLE work_schedules (
      id INT AUTO_INCREMENT PRIMARY KEY,
      work_date DATE NOT NULL,
      work_time TIME NOT NULL
  );

Why does the timezone of NOW() shift?

Answer

First, let’s check the current settings.
SHOW VARIABLES LIKE '%time_zone%';
To change the setting:
SET SESSION time_zone = 'Asia/Tokyo';

Can the precision of NOW() be set to milliseconds?

Answer

From MySQL 5.6 onward, you can obtain fractional seconds (milliseconds).
SELECT NOW(3);
Sample output (example)
2025-02-01 14:30:45.123

When storing data with millisecond precision

CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_time DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3)
);

Summary

  • NOW() and CURRENT_TIMESTAMP are basically the same, but use CURRENT_TIMESTAMP for column default values
  • Use UTC_TIMESTAMP() to get UTC time
  • DATETIME is a fixed value, TIMESTAMP is converted according to timezone
  • Use NOW(3) to retrieve milliseconds
  • If the timezone shifts, run SET SESSION time_zone = 'Asia/Tokyo';

9. Summary

How to Get the Current Time in MySQL

NOW()Retrieve the current date and time (YYYY-MM-DD HH:MM:SS)CURRENT_TIMESTAMPCan be used as a column default valueCURDATE()Retrieve only today’s dateCURTIME()Retrieve only the current timeUTC_TIMESTAMP()Always retrieve the UTC time

How to Format the Current Time in MySQL

✅ Using DATE_FORMAT(), you can convert dates and times into a readable format.
SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i');

Date Calculations Using the Current Time in MySQL

Get a future date
SELECT DATE_ADD(NOW(), INTERVAL 7 DAY);
Get a past date
SELECT DATE_SUB(NOW(), INTERVAL 30 DAY);
Calculate the difference between two dates
SELECT TIMESTAMPDIFF(DAY, '2025-01-01', NOW());
Convert a time to seconds
SELECT TIME_TO_SEC('01:30:00');

Time Zone Management

Check the current time zone
SHOW VARIABLES LIKE '%time_zone%';
Change the time zone to Japan Standard Time (JST)
SET SESSION time_zone = 'Asia/Tokyo';
How to retrieve UTC time
SELECT UTC_TIMESTAMP();
Convert time with time zone awareness
SELECT CONVERT_TZ(NOW(), 'UTC', 'Asia/Tokyo');

Practical Use Cases

Log management (automatic recording of creation and update timestamps)
CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Schedule management (calculating future dates)
INSERT INTO schedule (event_name, event_date) 
VALUES ('Project deadline', DATE_ADD(NOW(), INTERVAL 7 DAY));
Delete old data (remove records older than 30 days)
DELETE FROM logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY);

Key Takeaways

📌 Comprehensive guide to retrieving the current time in MySQL 📌 Explanation of how to use formatting and date calculations 📌 Showcase of practical examples useful in real-world scenarios (log management, schedule management, etc.) 📌 Detailed discussion of common errors and their solutions Time management in MySQL is useful for a variety of purposes, such as logging, data expiration handling, and schedule management. Master the appropriate functions and become able to implement time handling that meets your system requirements.