Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zeros from %m and %d in MySQL date_format

The following query produces a date that looks like this 2016, 01, 02. How do I get it to remove trailing zeros from the month and day so that it looks like this 2016, 1, 2?

SELECT DATE_FORMAT(earning_created, '%Y, %m, %d') AS day, SUM(earning_amount) AS amount
FROM earnings
WHERE earning_account_id = ?
GROUP BY DATE(earning_created)
ORDER BY earning_created
like image 524
Amy Neville Avatar asked Jan 02 '16 11:01

Amy Neville


People also ask

How do I remove leading zeros from a date in SQL?

In Oracle Database, you can use the fm (fill mode) format modifier to suppress any leading zeroes that might be applied to a date. This format modifier suppresses padding, which includes leading zeros and trailing blanks.

How do I insert date in YYYY-MM-DD format in MySQL?

You can use str_to_date to convert a date string to MySQL's internal date format for inserting.

How do I change the date format in MySQL workbench?

The current date format is 'YYYY-mm-dd'. To change current date format, you can use date_format().


1 Answers

You can use %c to format the month without the leading zero and %e to format the day of the month:

SELECT   DATE_FORMAT(earning_created, '%Y, %c, %e') AS day, -- Here! 
         SUM(earning_amount) AS amount
FROM     earnings
WHERE    earning_account_id = ?
GROUP BY DATE(earning_created)
ORDER BY earning_created
like image 124
Mureinik Avatar answered Nov 15 '22 17:11

Mureinik