🗓️

Working with Date and Time in MySQL

Oct 16, 2024

Getting Current Date and Time in MySQL

Overview

  • Purpose: Learn how to get the current date and time using MySQL and perform basic operations.
  • Activity: Create a temporary table to practice inserting and manipulating date and time values.

Steps

Create a Temporary Table

  1. Table Name: test
  2. Columns:
    • my_date with data type DATE
    • my_time with data type TIME
    • my_date_time with data type DATETIME
  3. Create Table: Use SQL command to create the table.
  4. Verify Creation: Select all from test to check if columns exist.

Inserting Current Date and Time

  1. Functions Used:
    • current_date(): Returns the current date.
    • current_time(): Returns the current time.
    • now(): Returns the current date and time.
  2. Insert Statement: Use these functions to insert values into test table.
  3. Display Results: Select all from test to view inserted date and time.

Example

  • Date and Time Example:
    • Current date: October 21, 2022
    • Current time: 7 AM
    • Current date time: October 21, 2022, 7 AM

Manipulating Date and Time

  • Increment/Decrement Date:
    • current_date + 1: Represents next day (e.g., October 22, 2022).
    • current_date - 1: Represents previous day (e.g., October 20, 2022).
  • Time Manipulation: Similar addition/subtraction can be done with time.

Clean Up

  • Drop Table: DROP TABLE test; to remove the temporary table.

Conclusion

  • This session explains how to retrieve and manipulate current date, time, and date-time in MySQL, using temporary tables for demonstration.