How to: Prompt for a Natural Language Date and parse with Templater

Things I have tried

I’ve included date:: <% await tp.system.prompt("Date") %> in my template which prompts to enter a simple string which will be inserted into the note when Templater runs.

What I’m trying to do

I have a folder template configured with Templater for meetings. In it, I want to include the date of the meeting. The date of the meeting is usually today but sometimes I create a meeting note in advance (e.g. if I want to build an agenda). Ideally I’d like to parse the date from a natural language date (e.g. @Today). I have the NLD plugin installed which has a hotkey action to parse and insert a natural language date. Is it possible to access any APIs from the Natural Language Date plugin to make this possible?

1 Like

Perhaps you’re making things more difficult than they need to be. How about instead just having the prompt for the date default to the current day, since that is your most common need?

date:: <% await tp.system.prompt("Date",tp.date.now()) %>

Note, this uses the default format of ‘YYYY-MM-DD’ for the date, so if you did this for today it would show 2022-08-12 in the default value of the prompt (which you can change if desired). If you prefer a different date style then you could supply a format string as a parameter to the now function. For example:

date:: <% await tp.system.prompt("Date",tp.date.now('MMMM D, YYYY')) %>

All the formatting options can be found at https://momentjs.com/docs/#/displaying/format/

You’re probably right–that’s what I was doing to start. It might sound silly but I use different date systems for work and non-work scenarios and sometimes mix up the month-date order :see_no_evil:, which I why I love using natural language dates. I ended up writing a user script which prompts for input and parses the NLD format, which is probably a bit brittle since it relies on the NLD plugin’s implementation but it works for my case for now.

I ended up writing a Templater user script and referencing it in the template.

In the Template

**Date**:: <% await tp.user.promptAndParseNaturalLanguageDate(tp) %>

User Script

const defaultDate = 'Today';

async function promptAndParseNaturalLanguageDate(params) {
  let prompt = defaultDate;
  if (params.quickAddApi) {
    // if calling via a QuickAdd macro
    prompt =  await params.quickAddApi.inputPrompt("Date", defaultDate, defaultDate);
  } else if (params.system) {
    // if calling from a template (requires passing `tp` as params)
    prompt = await params.system.prompt("Date", defaultDate);
  }

  const { parser, settings } = app.plugins.plugins["nldates-obsidian"];

  const parsed = parser.getParsedDate(prompt);
  const dateString = moment(parsed).format(settings.format);
  return `[[${dateString}]]`;
}

module.exports = promptAndParseNaturalLanguageDate;

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.