Calculate your age using Templater

Hey everyone – here’s a neat little code that can add your age in whatever format you want to your daily notes. I use it to generate my age on each daily note in the YAML metadata like age: 27.3.20 where you have years.months.days old.

async function calcAge(tp) {

var years = moment(tp.file.title).diff(moment('xxxxxxxx', 'YYYYMMDD'), 'years');
var totalMonths = moment(tp.file.title).diff(moment('xxxxxxxx', 'YYYYMMDD'), 'months');
var daysInMonth = moment(tp.file.title).daysInMonth();
var today = moment(tp.file.title).format("DD");

var months = totalMonths - (years * 12);
var days; 

if (moment(tp.file.title).format("DD") < xx) { days =
daysInMonth - (xx - moment(tp.file.title).format("DD"));
} else { days = moment(tp.file.title).format("DD") - xx };

let yeartxt = years.toString();
let monthtxt = months.toString();
let daytxt = days.toString();


let age = yeartxt.concat(".", monthtxt, ".", daytxt);
return age;
}

module.exports = calcAge

You have to fill in a couple things. 1) Your complete birthday in var years and var totalMonths, and your birthday day in the ‘if-else’ section. I marked them all with xx’s.

You need the Templater plugin, a folder for your js script being pointed to in the Templater settings, and the js file in the folder (e.g. calcAge.js). Then you need a template (e.g. Template - Calculate Age) with the script call: e.g. <% tp.user.calcAge(tp) %>.

Let me know if you have any ideas or suggestions!

3 Likes

Updated code:

async function calcAge(tp) {

//add your birthday here like YYYYMMDD
const birthday = 0;
// and the specific day like DD
const day = 0;

let years = moment(tp.file.title).diff(moment(birthday, 'YYYYMMDD'), 'years');
let totalMonths = moment(tp.file.title).diff(moment(birthday, 'YYYYMMDD'), 'months');
let daysInMonth = moment(tp.file.title).daysInMonth();
let today = moment(tp.file.title).format("DD");

let months = totalMonths - (years * 12);
let days; 

if (moment(tp.file.title).format("DD") < day) { days =
daysInMonth - (day - moment(tp.file.title).format("DD"));
} else { days = moment(tp.file.title).format("DD") - day };

let age = `${years}.${months}.${days}`;
return age;
}

module.exports = calcAge
2 Likes