date add string
Why this script
MySQL has a DATE_ADD function which can add time-units to a given date. These units can be expressed with a keyword such as DAY or WEEK combined with a quantity (1 DAY, 1 WEEK).
This function requires that you express the units using these (native) keywords which poses limitations to it's usage. This makes it impossible, for example, to store the unit-types in a database field, because they'll have to be stored as a string and can't be converted back into a keyword.
This function complements mysql's native DATE_ADD by offering the same functionality, but working with strings instead of keywords.
When is this usefull
A possible scenario where this is usefull:
You sell services or products which have to be invoiced with a certain interval. So, service A has to be invoiced every 14 days and product B has to be invoiced every month. This custom function makes it possible to simply store the service or product in a database table together with the interval and directly calculate when the next invoice has to be generated.
With MySQL's native DATE_ADD this would not be possible.
date / datetime
Because there are two formats with a date-component - DATE and DATETIME - i've created two functions as well:
- DATE_ADD_STR
- DATETIME_ADD_STR
Both work exactly in the same way except that the first returns the date formatted as YYYY-mm-dd and the second returns it as YYYY-mm-dd HH:ii:ss
The reason for this is that you have to define a return type in stored functions and mysql doesn't support the concept of overloading.
datesub
MySQL also has a native DATE_SUB function which does exactly the same as DATE_ADD, except that it substracts instead of adds to the date.
That's why I've included a DATETIME_SUB_STR and DATE_SUB_STR as well.