Open In App

MySQL NOW() function

Last Updated : 23 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The NOW() function in MySQL is a powerful tool that returns the current date and time based on the server’s time zone. This function is widely used when you need to capture the exact moment an event occurs such as when recording timestamps for records like orders, deliveries, or log entries.

In this article, We will learn about the MYSQL NOW() function by understanding various examples in detail.

MySQL NOW() function

  • The NOW() function in MySQL is used to return the current date and time based on the servers time zone.
  • It provides the date and time in the format YYYY-MM-DD HH:MM:SS.
  • The date and time returned by the NOW() function in MySQL are either in ‘YYYY-MM-DD HH:MM:SS’ format or ‘YYYYMMDDHHMMSS.uuuuuu’ format, depending on whether the function is used in a string or numeric context.

Syntax:

MySQL NOW function syntax is:

NOW()

Parameter

This method does not accept any parameters.

Examples of MySQL NOW() Function

Let’s look at some examples of the NOW function in MySQL. Learning the MySQL NOW function with examples will help you understand the concept better.

Example 1:

In this example, we are finding the current date and time using the NOW function. Here we will get the result in ‘YYYY-MM-DD HH:MM:SS’ format.

Query:

SELECT NOW() 
AS CurrDateTime ;

Output :

CURRDATETIME
2020-11-26 18:37:42

Example 2:

In this example, we are getting the current date and time using NOW Function in numeric format. Here the result will be in YYYYMMDDHHMMSS.uuuuuu format.

SELECT NOW()+ 0 
AS CurrDateTime ;

Output :

CURRDATETIME
20201126183839

Example 3:

In this example, we use the NOW function to set the value of the columns.

First, let’s create a table named DeliveryDetails.

CREATE TABLE Product (
ProductId INT NOT NULL,
ProductName VARCHAR(20) NOT NULL,
Delivered_At TIMESTAMP NOT NULL,
PRIMARY KEY(ProductId)
);

Here, we will use the NOW function to determine when a delivery will be completed. The value in Delivered_At column will be the value given by the NOW function.

INSERT INTO  
Product (ProductId, ProductName, Delivered_At)
VALUES
(1010, 'Apple MacBook', NOW());

Now, check the Product table :

SELECT * FROM Product;

Output:

PRODUCTID PRODUCTNAME DELIVERED_AT
1010 Apple MacBook 2021-10-01 14:41:15

Conclusion

The MySQL NOW() function is essential for capturing real-time data in your applications. Whether you are creating records with precise timestamps or performing time-sensitive operations, NOW() ensures that your database accurately reflects the current moment. Use this function wisely, considering server time zone configurations, to achieve accurate and reliable results



Next Article
Article Tags :

Similar Reads