w3resource

MySQL Date and Time Exercises: Get the current date in the following format

MySQL Date Time: Exercise-7 with Solution

Write a MySQL query to get the current date in the following format.

Sample date : 2014-09-04
Output : September 4, 2014

Code:

-- This SQL query formats the current date in a specified format and aliases it as 'Current_date'.

SELECT 
    DATE_FORMAT( -- Formats a date value according to the specified format.
CURDATE(), -- Retrieves the current date using the CURDATE() function.
        '%M %e, %Y' -- Specifies the desired format for the date: '%M' for full month name, '%e' for day of the month without leading zeros, and '%Y' for four-digit year.
    ) 
    AS 'Current_date'; -- Alias for the formatted current date.

Explanation:

  • The DATE_FORMAT() function is used to format a date value according to the specified format.
  • CURDATE() retrieves the current date.
  • The format string '%M %e, %Y' specifies the desired format for the date:
    • %M represents the full month name (e.g., January, February).
    • %e represents the day of the month without leading zeros (e.g., 1, 2, 3...).
    • %Y represents the four-digit year (e.g., 2024).
  • The formatted date is aliased as 'Current_date'.

Sample Output:

Current_date
August 11, 2017

 

MySQL Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a MySQL query to calculate the age in year.
Next:Write a MySQL query to get the current date in Thursday September 2014 format.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mysql-exercises/date-time-exercises/write-a-query-to-get-the-current-date-in-the-following-format.php