Space Script: addTimeToDate

Thanks to ChatGPT i made this Space-Script for my use.

How to use:
{{addTimeToDate(date,increment,‘unit’)}}

where:

  • date: initial date
  • increment: number to add to the date
  • unit: d = days / w = weeks / m = month / y = year

Examples:
{{addTimeToDate(today,10,‘d’)}} // Aggiungi 2 mesi

adding 10 days, {{addTimeToDate(today,10,‘d’)}}
adding 1 days, {{addTimeToDate(yesterday,1,‘d’)}}
adding -1 days: {{addTimeToDate(tomorrow,-1,‘d’)}}
adding -1 week: {{addTimeToDate(nextWeek,-1,‘w’)}}

Today is {{today}}, adding 10 days, result: {{addTimeToDate(today,10,'d')}}
Yesterday was {{yesterday}}, adding 1 days, result: {{addTimeToDate(yesterday,1,'d')}}
Tomorrow is {{tomorrow}}, adding -1 days, result: {{addTimeToDate(tomorrow,-1,'d')}}

nextWeek is {{nextWeek}} adding -1 week, result: {{addTimeToDate(nextWeek,-1,'w')}}
silverbullet.registerFunction({name: "addTimeToDate"}, (initialDate, increment, unit) => {
    const date = new Date(initialDate);
    switch (unit.toLowerCase()) {
        case 'd':
            date.setDate(date.getDate() + increment);
            break;
        case 'w':
            date.setDate(date.getDate() + (increment * 7));
            break;
        case 'm':
            date.setMonth(date.getMonth() + increment);
            break;
        case 'y':
            date.setFullYear(date.getFullYear() + increment);
            break;
        default:
            throw new Error('Increment unit not supported');
    }
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); 
    // Aggiunge uno perche' i mesi partono da 0
    const day = date.getDate().toString().padStart(2, '0');
    // Restituisci la data nel formato YYYY-MM-DD
    return `${year}-${month}-${day}`;
})
3 Likes

Could something similar to this be made to adjust for time zones, so that anytime a date/time stamp is created, it will adjust by a set number of hours? For example, I live in Texas, so I am currently UTC -5 . If I create a new quick note at 9 pm local time, the note will stamped 2 am tomorrow. No bueno. Thanks for any thoughts you may have

I’m not a programmer, the script was written for my use and I hope someone whit better skills can improve it.