Changing year in mysql date

前端 未结 5 2092
野的像风
野的像风 2021-01-03 18:03

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

相关标签:
5条回答
  • 2021-01-03 18:41
    UPDATE tableName
    SET    dateColumn = dateColumn + INTERVAL 4 YEAR
    
    • SQLFiddle Demo

    other way is to concatenate it,

    UPDATE Table1
    SET    DateColumn = CONCAT(YEAR(CURDATE()), '-', DATE_FORMAT(dateColumn, '%m-%d'))
    
    • SQLFiddle Demo
    0 讨论(0)
  • 2021-01-03 18:55

    Current date from quest was 2013, I understand that you wish set current YEAR in date.

    UPDATE table_name SET date_col=DATE_FORMAT('2013-05-06',YEAR(CURRENT_DATE)-%m-%d);
    
    0 讨论(0)
  • 2021-01-03 18:56

    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');
    
    0 讨论(0)
  • 2021-01-03 18:59

    If its a date field:

      UPDATE table_name SET date_field_name = CONCAT("2013", RIGHT(date_field_name,6));
    

    If its a date time field:

    UPDATE table_name SET date_field_name = CONCAT("2013", RIGHT(date_field_name,15));
    
    0 讨论(0)
  • 2021-01-03 19:00

    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

    0 讨论(0)
提交回复
热议问题