Home > other >  storing datetime modifications formats
storing datetime modifications formats

Time:03-02

I have a requirement where the user wants to be able to save "Date Modifier" strings to a database, and then use that with other dates in their application.

e.g. -

id   name              date_modifier
1    Add 1 Year         1 year
2    Last Day Of Month last day of this month

// simplified; using DateTime
echo $date->modify($date_modifier);
// today = 02/03/2022
// Add 1 Year = 02/03/2023
// Last day of month = 31/03/2023

Essentially I'm passing a date modifier string to a DateTime object to modify it.

This seems to be working OK but I am running into issues -

For example; some of the requirements are 5th of {whatever date is supplied} this isn't working / I don't know what a date modifier looks like to achieve this.

$date = '02/03/2022';
$date->modify($fifth_of_month);
// outputs 05/03/2022

My next thought was to also store date_format so I wouldn't modify this date; but I would format it as $date->format('Y-m-05')

Is there a better approach to this as this looks like it could get very messy very quickly?

CodePudding user response:

User can have endless weird requests for an option like this. For instance: "Next leap year last day of February". OK, I might be overdoing it, but these dates can be relative, absolute or a mixture. Predicting what user want is always difficult. You need to be flexible.

In cases like this I usually don't even try to find a cute solution, because there will come a time you have to ditch it and start again. My solution? The simple switch:

switch ($wantedModification) {
    case 'Add 1 year'        : $newDate = $date->modify(' 1 year');
                               break;
    case 'Last Day Of Month' : ....
                               break;
    case '5th of next Month' : ....
                               break;
    default : alert('Sorry, I forgot to implement this choice...');
              break; 
}

(code is just an example, and not meant to be correct)

This way you can easily incorporate any weird request that might come your way, and you get to keep your existing work. This is not the shortest solution, or the cleverest, but it is the most practical.

  • Related