Date and Time Functions

Describes some commonly used date and time functions like, CURRENT_DATE(), CURRENT_TIME(), and EXTRACT().

MySQL supports a number of built-in functions that allows you to manipulate dates and times. Some commonly used date and time functions are listed below.

Examples of using date and time functions, DateTimeFunctions.sql:

-- DateTimeFunctions.sql
-- Copyright (c) 1999 HerongYang.com. All Rights Reserved.
--
SELECT CURRENT_TIME();
SELECT EXTRACT(HOUR FROM CURRENT_TIME());
SELECT EXTRACT(MONTH FROM TIMESTAMP'1999-02-28 10:20:30');
SELECT DATE('2023-2-3 01:02:03');
SELECT DATE('2023/2/3 01:02:03');
SELECT DATE(CONCAT_WS('-', 1, 2, 3));
SELECT MAKEDATE(2014, 365);
SELECT MAKETIME(12, 15, 30);
SELECT TIME('2003-12-31 01:02:03.000123');

Output:

CURRENT_TIME()
21:38:37
EXTRACT(HOUR FROM CURRENT_TIME())
21
EXTRACT(MONTH FROM TIMESTAMP'1999-02-28 10:20:30')
2
SELECT DATE('2023-2-3 01:02:03');
'2023-2-3'
SELECT DATE('2023/2/3');
'2023-2-3'
SELECT DATE(CONCAT_WS('-', 1, 2, 3));
'0001-02-03'
SELECT MAKEDATE(2014, 365);
'2014-12-31'
SELECT MAKETIME(12, 15, 30)
'12:15:30'
SELECT TIME('2003-12-31 01:02:03.000123');
'01:02:03.000123'

By the way, there date function to return the date of a given year, month and day of the month. The best way is use DATE(CONCAT_WS('-', year, month, day)) as shown in the above example.

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 PHP Programs and MySQL Server

 Perl Programs and MySQL Servers

 Java Programs and MySQL Servers

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

Commonly Used Functions

 Flow Control Functions

 Character String Functions

 Numeric Value Functions

Date and Time Functions

 JSON Document Functions

 XML Document Functions

 Spatial Data Functions

 Cast Function

 Table Column Types for Different Types of Values

 Using DDL to Create Tables and Indexes

 Using DML to Insert, Update and Delete Records

 Using SELECT to Query Database

 Window Functions for Statistical Analysis

 Use Index for Better Performance

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 System, User-Defined and Stored Procedure Variables

 MySQL Server Administration

 Storage Engines in MySQL Server

 InnoDB Storage Engine - Primary and Secondary Indexes

 Performance Tuning and Optimization

 Bulk Changes on Large Tables

 MySQL Server on macOS

 Installing MySQL Server on Linux

 Connection, Performance and Second Instance on Linux

 Archived Tutorials

 References

 Full Version in PDF/EPUB