Trying to integrate a script that can calculate age from birthdate in months and years

But I’m a bit stuck in how to integrate functions I’ve found that do this online with the actual usage. I’d like to replace existing text (or prepend) the age. The birthdate will be hardcoded in the script.

This Stack Overflow thread has a few basic Javascript function examples that can calculate age from a date. Any of these should work fine in a Drafts script action.

Using one of these, something like this…

let birthday = Date.parse("1/1/1970"); // use actual birthday!

// example from Stack Overflow, may not do exactly what you want
function calculateAge(birthday) { // birthday is a date
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}
let age = calculateAge(birthday); // age in years

// replace current selection with new value in Drafts
editor.setSelectedText(age);

Here’s an action that does years, months and days, so you can just drop the days to do the months and years. You would obviously need to change the initial date, and you might want to enhance it a bit to drop the years/months should either be zero.

https://actions.getdrafts.com/a/1PP

Hope that helps.

1 Like

This is SO helpful. Thank you so much. Hopefully it’s not pushing it too much to ask how I’d prepend the outcome to the current draft? I can’t figure out how to do that.

In a script, to prefix some content you could just do this.

draft.content = "some content" + draft.content;
draft.update();

You could also do this using the editor object, but if you are not working with cursor position, I think working with the draft object is better. It would certainly allow for operating on multiple drafts if you were working in batch.

Hopefully that’s a big enough clue for you to figure out how to apply it to one of the actions posted above.

Perfect. Thanks so much. Got it all figured out now.