Resources | Subject Notes | Information Communication Technology ICT
This section focuses on how to control the format in which date and time data is displayed within a database. Different database systems offer various formatting options, allowing you to present data in a user-friendly and consistent manner.
Databases typically store date and time information using specific data types. Common types include:
The available formatting options depend on the database management system (DBMS) being used. Common formats include:
Here are examples of how to format date and time data in some popular DBMS:
MySQL uses the DATE_FORMAT()
function.
SQL | Output |
---|---|
SELECT DATE_FORMAT(your_date_column, '%d/%m/%Y') AS formatted_date FROM your_table; |
Example: 27/10/2023 |
SELECT DATE_FORMAT(your_datetime_column, '%H:%i:%s %p') AS formatted_time FROM your_table; |
Example: 02:30:00 PM |
SQL Server uses the CONVERT()
function with style codes.
SQL | Output |
---|---|
SELECT CONVERT(VARCHAR, your_date_column, 103) AS formatted_date FROM your_table; |
Example: 10/27/2023 |
SELECT CONVERT(VARCHAR, your_datetime_column, 108) AS formatted_time FROM your_table; |
Example: 2:30:00 PM |
PostgreSQL uses the TO_CHAR()
function.
SQL | Output |
---|---|
SELECT TO_CHAR(your_date_column, 'DD/MM/YYYY') AS formatted_date FROM your_table; |
Example: 27/10/2023 |
SELECT TO_CHAR(your_datetime_column, 'HH24:MI:SS') AS formatted_time FROM your_table; |
Example: 14:30:00 |
Maintaining consistent date and time formatting is crucial for:
Practice using the appropriate formatting functions for the specific DBMS you are working with. Experiment with different format codes to achieve the desired output.