Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing year in mysql date

Tags:

date

mysql

I have a bunch of dates in our database stored in the standard mysql date type.

How can I covert a year to 2013, regardless of original date.

So if a date is 2009-01-01 it would be 2013-01-01, but if it's 2012-01-04, it'd convert to 2013-01-14.

I figured it'd be simple and obvious, but I couldn't figure it out =/

like image 339
Andelas Avatar asked Jan 24 '13 00:01

Andelas


People also ask

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

MySQL uses yyyy-mm-dd format for storing a date value. This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want.

How do I add years to a date in MySQL?

DATE_ADD() function in MySQL is used to add a specified time or date interval to a specified date and then return the date. Specified date to be modified. Here the value is the date or time interval to add.

How do I format a date in MySQL?

MySQL retrieves and displays DATE values in ' YYYY-MM-DD ' format. The supported range is '1000-01-01' to '9999-12-31' . The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format.


2 Answers

That's simple:

for DATETIME:

UPDATE table_name SET date_col=DATE_FORMAT(date_col,'2013-%m-%d %T'); 

for DATE:

UPDATE table_name SET date_col=DATE_FORMAT(date_col,'2013-%m-%d'); 
like image 160
Adi Avatar answered Sep 22 '22 05:09

Adi


The problem with the current answers is that none of them take leap year into account. If you take the date '2016-02-29' and convert it to the year 2013 through concatenation, you get '2013-02-29', which is not a valid date. If you run DATE_FORMAT('2013-02-29', '%Y-%m-%d') the result is null. See an example here:

http://sqlfiddle.com/#!9/c5358/11

A better way to change the year is to use DATE_ADD since it accounts for daylight savings. For example:

SELECT DATE_FORMAT(DATE_ADD(datecol, INTERVAL (YEAR(CURRENT_DATE()) - YEAR(datecol)) YEAR), '%Y-%m-%d') `date` FROM t; 

You could substitute CURRENT_DATE() with '2013-01-01' if you still wanted to convert all dates to 2013 instead of the current year. An example of this solution is here:

http://sqlfiddle.com/#!9/c5358/12

like image 30
recneps Avatar answered Sep 21 '22 05:09

recneps