Template Tool kit - Subtract days from a given date in the template

147 views Asked by At

First, I don't have access to the code I have to try to do this on the template.

I have a date that will be available on the template [%UserDate%]

I need to subtract 120 days from the provided [%UserDate%] value.

<div>
120 Days Before:  [%UserDate%]
</div>

I tried to find a way to to this here:
http://template-toolkit.org/docs/modules/Template/Plugin/Date.html
and here:
https://metacpan.org/pod/Date::Calc

But either I am lost or can not find a method or way to do it.

1

There are 1 answers

4
Dave Cross On BEST ANSWER

Assuming a) that UserDate is just a string and nothing useful like a DateTime object and b) that you have Date::Calc installed, then this seems to get you most of the way there:

[% UserDate = '05/12/2023' -%]
[% UserDateArray = UserDate.split('/') -%]
[% USE date -%]
Original date: [% UserDate %]
120 days before: [% date.calc.Add_Delta_Days(UserDateArray.2,
                                             UserDateArray.1,
                                             UserDateArray.0,
                                             -120).reverse.join('/') %]

Testing it with tpage:

$ tpage days.tt
Original date: 05/12/2023
120 days before: 7/8/2023

I've assumed that the date you've mentioned is dd/mm/yyyy. If you're using another, less logical date format then you'll need to adjust the order of the parameters you're passing to Add_Delta_Days().