SupportOfficer2
SupportOfficer2

Reputation: 23

How can I convert date format from YYYY-MM-DD to YYYY-MM in sql

I have a specific date in the format of YYYY-MM-DD but want to convert it to YYYY-MM format in a table. I want this change to apply to the full table. can anyone help me out, please? Thank you.

Upvotes: 1

Views: 901

Answers (2)

Ved
Ved

Reputation: 746

You can use DATE_FORMAT function of MySQL, for more information please visit

SELECT DATE_FORMAT("2017-06-15", "%Y-%m"); 

Upvotes: 1

GMB
GMB

Reputation: 222482

Assuming that you have a date datatype or the-like (datetime, timestamp), you can use date_format() to represent your date in the target format:

date_format(mydate, '%Y-%m')

This returns a string in the target format. It does not make sense to convert your date column to a string though. Keep that column as it is, and maybe use a computed column to automatically derived the string representation you want:

create table mytable (
    ...
    mydate date,
    mynewcol varchar(7) as (date_format(mydate, '%Y-%m'))
)

Upvotes: 4

Related Questions