MySQL - LOCALTIME() Function



The MYSQL LOCALTIME() function is used to get the current date and time value. The resultant value is a string or a numerical value based on the context and, the value returned will be in the 'YYYY-MM-DD hh:mm:ss' or YYYYMMDDhhmmss format.

We can also use LOCALTIME instead of LOCALTIME(). These are synonyms for the NOW() function. The MySQL NOW() function is used to get the current date and time value.

Syntax

Following is the syntax of MySQL LOCALTIME() function −

LOCALTIME();

Parameters

This method does not accept any parameters.

Return value

This function returns the current local system date and time as a DATETIME value.

Example

Following example demonstrates the usage of the LOCALTIME() function −

SELECT LOCALTIME() As Result;

Output

This will produce the following result −

Result
2023-11-13 15:51:37

Example

Here, we are adding 0 to the current local time. The "+0" serves as a simple way to convert the time to a numeric representation

SELECT LOCALTIME()+0 As Result;

Output

Following is the output −

Result
20231113155137

Example

We can add seconds to the current time stamp as shown below −

SELECT LOCALTIME()+12 As Result;

Output

Following is the output −

Result
20231113155149

Example

We can also subtract the desired number of seconds from the current time using this function −

SELECT LOCALTIME()-12 As Result;

Output

Following is the output −

Result
20231113155125

Example

We can use LOCALTIME instead of LOCALTIME() to retrieve the current time −

SELECT LOCALTIME  As Result;

Output

Following is the output −

Result
2023-11-13 15:51:37

Example

In this example, we have created a table named ORDERS using the following CREATE TABLE query

CREATE TABLE ORDERS (
   OID INT NOT NULL,
   DATE VARCHAR (20) NOT NULL,
   CUSTOMER_ID INT NOT NULL,
   AMOUNT DECIMAL (18, 2)
);

Now, insert the following records into the ORDERS table using the INSERT statement −

INSERT INTO ORDERS VALUES 
(102, '2009-10-08 00:00:00', 3, 3000.00),
(100, '2009-10-08 00:00:00', 3, 1500.00),
(101, '2009-11-20 00:00:00', 2, 1560.00),
(103, '2008-05-20 00:00:00', 4, 2060.00);

Execute the below query to fetch all the inserted records in the above-created table −

Select * From ORDERS;

Following is the ORDERS table −

OID DATE CUSTOMER_ID AMOUNT
102 2009-10-08 00:00:00 3 3000.00
100 2009-10-08 00:00:00 3 1500.00
101 2009-11-20 00:00:00 2 1560.00
103 2008-05-20 00:00:00 4 2060.00

The following query calculates the difference in DAYS between the "DATE" and "LOCALTIME" columns −

SELECT OID, DATE, LOCALTIME, TIMESTAMPDIFF(DAY, DATE, LOCALTIME) 
As RemainingDays FROM ORDERS;

Output

The output is displayed as follows −

OID DATE LOCALTIME RemainingDays
102 2009-10-08 00:00:00 2023-11-13 16:01:08 5149
100 2009-10-08 00:00:00 2023-11-13 16:01:08 5149
101 2009-11-20 00:00:00 2023-11-13 16:01:08 5106
103 2008-05-20 00:00:00 2023-11-13 16:01:08 5655
Advertisements