gorootde / silverbullet-collection

Collection of awesome silverbullet.md stuff
GNU General Public License v3.0
54 stars 1 forks source link

Show age when using DaysTillBirthday #6

Closed paletochen closed 6 months ago

paletochen commented 6 months ago

Hi,

Is it possible to show the age when using DaysTillBirthday in a query?

Example: I'd like to have something like this

[[name]] 🎂 in 1 days (35 years)

Thanks

paletochen commented 6 months ago

I figure it out.

```space-script
silverbullet.registerFunction("daysTillBirthdayAndAge", (date) => {
  const birthDate = Temporal.PlainDate.from(date);
  const now = Temporal.Now.plainDateISO();
  const thisYearBirthday = new Temporal.PlainDate(now.year, birthDate.month, birthDate.day);

  const age = now.year - birthDate.year;

  if (now.equals(thisYearBirthday)) {
    return { days: 0, age }; // Happy Birthday!
  } else if (Temporal.PlainDate.compare(now, thisYearBirthday) < 0) {
    // Birthday is still coming this year
    return { days: now.until(thisYearBirthday, { largestUnit: 'days' }).days, age };
  } else {
    // Birthday has passed for this year, calculate for next year
    const nextYearBirthday = new Temporal.PlainDate(now.year + 1, birthDate.month, birthDate.day);
    return { days: now.until(nextYearBirthday, { largestUnit: 'days' }).days, age };
  }
});

Template `Library/Personal/Query/Person`

tags: template

And then the query like this:

```query
page where type = "person" and birthday != null render [[Library/Personal/Query/Person]] order by daysTillBirthdayAndAge(birthday).days limit 20
gorootde commented 6 months ago

You may also use something like Mike is {{floor(dateDiff(birthday, today()),"years") }} old to achieve the same. See DateDiff and MathBasics files in this repository.