How to use the MySQL LOCALTIME() function

MySQL LOCALTIME() is a function that returns the current date and time. It is a synonym for the NOW() function.

Posted on

MySQL LOCALTIME() is a function that returns the current date and time. It is a synonym for the NOW() function. The value is returned in ‘YYYY-MM-DD HH:MM:SS’ or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context. The function can be useful for getting the current timestamp, or for performing calculations based on the current time.

Syntax

The syntax of the function is:

LOCALTIME()

The function takes no arguments.

Examples

Some examples of using the function are:

  • To get the current date and time, use:

    SELECT LOCALTIME();
    

    The result is:

    2023-11-15 10:20:21
    

    This means that the current date and time is November 15, 2023, 10:20:21.

  • To get the current date and time in numeric format, use:

    SELECT LOCALTIME() + 0;
    

    The result is:

    20231115102021
    

    This means that the current date and time is 20231115102021.

  • To get the current date and time in a different format, use:

    SELECT DATE_FORMAT(LOCALTIME(), '%d/%m/%Y %h:%i:%s %p');
    

    The result is:

    15/11/2023 10:20:21 AM
    

    This means that the current date and time is formatted as day/month/year hour:minute:second AM/PM.

  • To get the current date and time in UTC, use:

    SELECT CONVERT_TZ(LOCALTIME(), @@session.time_zone, '+00:00');
    

    The result is:

    2023-11-15 08:20:21
    

    This means that the current date and time in UTC is November 15, 2023, 08:20:21.

  • To get the difference between the current date and time and a given date and time, use:

    SELECT TIMEDIFF(LOCALTIME(), '2023-11-01 00:00:00');
    

    The result is:

    361:20:21
    

    This means that the difference between the current date and time and November 1, 2023, 00:00:00 is 361 hours, 20 minutes, and 21 seconds.

Similar Functions

Some similar functions to LOCALTIME() are:

  • NOW(): This function is equivalent to the LOCALTIME() function. It returns the current date and time.
  • SYSDATE(): This function returns the time at which the function executes. It may differ from the LOCALTIME() function if the query takes a long time to execute.
  • CURDATE(): This function returns the current date. It is equivalent to the DATE(LOCALTIME()) function.
  • CURTIME(): This function returns the current time. It is equivalent to the TIME(LOCALTIME()) function.