How to convert a string to date/time in MySQL 8

Updated: January 26, 2024 By: Guest Contributor Post a comment

Introduction

Working with dates and times can frequently be a perplexing task when it involves managing data across different systems, formats, or locales. Especially in SQL databases like MySQL, ensuring that date and time strings are properly parsed and stored according to standards is critical for the integrity and functionality of the system. This article will guide you through the process of converting string data into date/time formats in MySQL 8, highlighting a diversity of methods and functions that MySQL provides.

Understanding Date/Time Data Types in MySQL

Before we dive into the conversion methods, it’s important to understand the various date and time data types available in MySQL. Here are the common ones:

  • DATE: Stores a date in ‘YYYY-MM-DD’ format.
  • DATETIME: Stores a date and time in ‘YYYY-MM-DD HH:MM:SS’ format.
  • TIMESTAMP: Similar to DATETIME, but also includes timezone support and ranges from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.
  • TIME: Represents a time, without date, formatted as ‘HH:MM:SS’.
  • YEAR: Stored as a 4-digit year.

Basic String to Date/Time Conversion

The most straightforward function for converting a string to a date or date/time in MySQL is the STR_TO_DATE() function. It takes a string and a format specifier and returns a formatted date:

SELECT STR_TO_DATE('2021-04-30', '%Y-%m-%d') AS formatted_date;

Output:

2021-04-30

This function is particularly useful for converting date strings of various formats by modifying the format specifiers according to the input string:

SELECT STR_TO_DATE('30/04/2021', '%d/%m/%Y') AS formatted_date;

Output:

2021-04-30

Formatting Strings as Time and Timestamps

Converting strings to time or timestamps follows the same principle, but the format specifiers will differ:

SELECT STR_TO_DATE('11:45:30', '%H:%i:%s') AS formatted_time;

Output:

11:45:30
SELECT STR_TO_DATE('2021-04-30 11:45:30', '%Y-%m-%d %H:%i:%s') AS formatted_datetime;

Output:

2021-04-30 11:45:30

Dealing with Locale-Specific Dates

When dealing with locale-specific dates, you need to ensure the proper locale is set on the MySQL server, and use the correct language-dependent format specifiers. You can use the lc_time_names system variable to set the locale:

SET lc_time_names = 'es_MX';
SELECT STR_TO_DATE('Abril 30 2021', '%M %d %Y') AS formatted_date;

Output:

2021-04-30

Handling NULL Values and Invalid Formats

What happens if the string is improperly formatted or cannot be converted? The STR_TO_DATE() function will return NULL. Therefore, it’s important to handle potential NULL values to prevent any unexpected behavior:

SELECT COALESCE(STR_TO_DATE('April 31 2021', '%M %d %Y'), 'Invalid Date') AS formatted_date;

Output:

Invalid Date

Advanced Parsing and Conversion Techniques

For strings that contain date and time data in complex or non-standard formats, you may need to employ MySQL expressions and functions in tandem to parse the string accordingly. You can use the SUBSTRING(), CONCAT(), and other string functions to manipulate and rebuild the string into a recognizable format before converting:

SELECT STR_TO_DATE(CONCAT(SUBSTRING('30th April 2021', 1, 2), ' ', 
  SUBSTRING('30th April 2021', 4, 99)), '%d %M %Y') AS formatted_date;

Output:

2021-04-30

Using CAST and CONVERT Functions

Alternatively, MySQL provides CAST() and CONVERT() functions for type casting, which can be used to convert data types:

SELECT CAST('2021-04-30' AS DATE) AS formatted_date;

Output:

2021-04-30

However, these functions are less flexible than STR_TO_DATE() when it comes to formatting and should be used when the input string format is clearly compliant with the expected date or datetime format.

Error Handling in Complex Conversions

In cases where your string-to-date/time conversion tasks are complex and prone to errors, you may want to incorporate error handling within Stored Procedures or use conditional logic like IF() or CASE statements to manage these potential pitfalls.

Example:

DELIMITER //

CREATE PROCEDURE ConvertStringToDate(IN input_string VARCHAR(255), OUT output_date DATE)
BEGIN
    DECLARE temp_date DATE DEFAULT NULL;

    -- Attempt to convert the string to a date
    SET temp_date = STR_TO_DATE(input_string, '%Y-%m-%d');

    -- Check if the conversion was successful
    IF temp_date IS NULL THEN
        -- Handle the error case (e.g., log the error, set default value, etc.)
        SET output_date = '1000-01-01'; -- Example: setting a default value
    ELSE
        -- If successful, set the output
        SET output_date = temp_date;
    END IF;
END //

DELIMITER ;

To use this procedure, you would call it with an input string and a variable to capture the output date. For example:

CALL ConvertStringToDate('2023-01-15', @output);
SELECT @output;

Explanation:

  1. Procedure Definition: ConvertStringToDate takes an input_string and returns an output_date. The OUT parameter is used to return the output.
  2. Conversion Attempt: The procedure uses STR_TO_DATE to attempt to convert the input_string into a DATE format. The format specified here is %Y-%m-%d, but you can modify this based on the expected format of your input string.
  3. Conditional Logic for Error Handling:
    • The IF statement checks if temp_date is NULL, indicating a failed conversion.
    • If the conversion fails (temp_date IS NULL), the procedure handles this by setting output_date to a default value (e.g., ‘1000-01-01’). You can replace this with any appropriate error handling mechanism, such as logging the error or setting a specific error flag.
    • If the conversion is successful, output_date is set to the converted date.

Conclusion

Converting strings to date/time in MySQL 8 involves understanding and leveraging the built-in functions and being cautious about potential errors and irregularities in data. Assuring your date and time data is accurately formatted and stored ensures reliability and facilitates temporal data analysis and operations.