Skip to content

TIMESTAMPDIFF calculations are wrong for time differences over ~292 years #10397

@angelamayxie

Description

@angelamayxie

We rely on Time.Sub to calculate differences between times in timestampdiff, but this doesn't work for timestamps with a difference greater than 9,223,372,036,854,775,807 nanoseconds, or ~292.47 years. This is because Time.Sub returns a Duration, which is really an int64 representing nanoseconds.

Since MySQL timestamps only go to microsecond precision, we can fix this by converting times to their microsecond values and subtracting them.

mysql>  select timestampdiff(microsecond, "0000-01-01", "9999-12-31 23:59:59.999999");
+------------------------------------------------------------------------+
| timestampdiff(microsecond, "0000-01-01", "9999-12-31 23:59:59.999999") |
+------------------------------------------------------------------------+
|                                                     315569433599999999 |
+------------------------------------------------------------------------+
1 row in set (0.00 sec)

The above is the largest timestampdiff value we should be able to support, which should be fine because it fits in an int64. (However, we should check if later dates like 9999-12-31 23:59:59.999999 properly convert to their microsecond values)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingcorrectnessWe don't return the same result as MySQL

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions