[Help] DateDiff in lua version

Hey folks,
I’m trying to learn the new way of using with Silverbullet with Lua but I am struggling with some basic changes.

Could anyone please help me understand how i could migrate this DateDiff space-script to lua?

Thanks

This script will calculate the diff between two given dates. Use the third parameter of the function to specify the unit of the result. e.g. `days`, `months` or `years`.

```space-script
silverbullet.registerFunction({name: "dateDiff"},(date1,date2,unit="days") => {
    const d1=Temporal.PlainDate.from(date1)
    const d2=Temporal.PlainDate.from(date2)
    const diff=d1.until(d2)
    return diff.total({unit,relativeTo:date1})
})
```

## Examples

```template
last week to today: {{dateDiff(lastWeek(),today())}} days
```

```template
Linus Torvalds is {{dateDiff("1969-12-28",today(),"years")}} years old
```

I’m suffering and this is just the 1st script from many that I use from here: GitHub - gorootde/silverbullet-collection: Collection of awesome silverbullet.md stuff
:sweat_smile:

Give this a try:

function dateDiff(date1, date2, unit)
    unit = unit or "days"

    local function parseDate(str)
        local year, month, day = str:match("(%d+)%-(%d+)%-(%d+)")
        return os.time({year=tonumber(year), month=tonumber(month), day=tonumber(day)})
    end

    local time1 = parseDate(date1)
    local time2 = parseDate(date2)

    local diffInSeconds = math.abs(time2 - time1)

    if unit == "days" then
        return math.floor(diffInSeconds / (60 * 60 * 24))
    elseif unit == "months" then
        -- Rough approximation, assumes 30.44 days in a month
        return math.floor(diffInSeconds / (60 * 60 * 24 * 30.44))
    elseif unit == "years" then
        return math.floor(diffInSeconds / (60 * 60 * 24 * 365.25))
    else
        error("Unsupported unit: " .. unit)
    end
end

${“Last week to today: " .. dateDiff(“2025-04-25”, “2025-05-02”, “days”) .. " days”}
${“Linus Torvalds is " .. dateDiff(“1969-12-28”, date.today(), “years”) .. " years old”}

4 Likes

Thank you so much!!!

I’ll try to use it as a template to learn :slight_smile: