Home > Database > Mysql Tutorial > How to Customize DATETIME Format in MySQL Table Creation?

How to Customize DATETIME Format in MySQL Table Creation?

DDD
Release: 2024-12-03 02:20:09
Original
399 people have browsed it

How to Customize DATETIME Format in MySQL Table Creation?

How to Configure DATETIME Format During Table Creation in MySQL

Creating a table with a DATETIME column is a common task in MySQL. However, you may encounter situations where you want to specify a specific format for the DATETIME values. This article explains how to set the default format for a DATETIME column to 'DD-MM-YYYY HH:MM:SS' during table creation using MySQL commands.

Default MySQL DATETIME Format

By default, MySQL stores and retrieves DATETIME values in the 'YYYY-MM-DD HH:MM:SS' format. This is the standard format used by MySQL and is often appropriate for many applications.

Specifying a Custom Format

To specify a custom format for a DATETIME column during table creation, you can use the TIME_FORMAT function. The following MySQL command demonstrates how to create a table with a DATETIME column formatted as 'DD-MM-YYYY HH:MM:SS':

CREATE TABLE my_table (
  id INT NOT NULL AUTO_INCREMENT,
  datetime_column DATETIME FORMAT TIME_FORMAT('%d-%m-%Y %H:%i:%s')
);
Copy after login

In this command, the TIME_FORMAT specifier is used to define the custom 'DD-MM-YYYY HH:MM:SS' format.

Note: The TIME_FORMAT function only affects the representation of DATETIME values stored in the database. The actual DATETIME values are still stored in the 'YYYY-MM-DD HH:MM:SS' format.

Displaying the Formatted Value

Once the table is created, you can use the DATE_FORMAT function to display the DATETIME values in the custom format:

SELECT id, DATE_FORMAT(datetime_column, '%d-%m-%Y %H:%i:%s') AS formatted_datetime
FROM my_table;
Copy after login

This will retrieve the id and the DATETIME column in the 'DD-MM-YYYY HH:MM:SS' format.

The above is the detailed content of How to Customize DATETIME Format in MySQL Table Creation?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template