wanasit / chrono

A natural language date parser in Javascript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Expose casual date match

zhouzi opened this issue · comments

I'm building an interface where the user can type "tmrw" and the autocomplete suggests "Tomorrow".

So I need to know which casual date matched.

There's already a switch in the casual parsers discrimating the different casual dates so I think it can be added with no breaking changes.

I'm looking into it and will suggest a PR.

@zhouzi Sorry for my slow reply. As mentioned in #525, outputting format text for all supported conditions and locales would be challenging.

From what you explained, the problem is you want to recognize the casual reference date (e.g. today, tomorrow) to treat them differently. I think that a reasonable use-case and I found it surprisingly difficult to do it with the current API.

I think this problem could be solved by the parsing tag (#534). Introducing tags is an idea that I have been thinking about for debugging parsers, but I think it also fits your use-case. Could you take a look at #534 and give me some feedback?

This has been solved by #534, here's how our code looks like:

const getCasualText = (parsedComponents: ParsedComponents) => {
  const tags = parsedComponents.tags();
  const translations = [
    ['casualReference/today', 'Today'],
    ['casualReference/yesterday', 'Yesterday'],
    ['casualReference/tomorrow', 'Tomorrow'],
    ['casualReference/now', 'Now'],
  ];

  for (const [tag, casualText] of translations) {
    if (tags.has(tag)) return casualText;
  }

  return undefined;
};

With this function it's possible to convert a parsed date to the appropriate string (Today/Yesterday/Tomorrow/Now). We don't need to translate to other languages but it wouldn't be too hard to do if we ever need it:

const translations = {
  "parser/ENCasualDateParser": [
    ['casualReference/today', 'Today'],
    ['casualReference/yesterday', 'Yesterday'],
    ['casualReference/tomorrow', 'Tomorrow'],
    ['casualReference/now', 'Now'],
  ],
  // ...other parsers
};

It's worth noting that tags are not added for all locales at the time of writing, which is fine for our use case. But if someone needs more tags they might want to send a PR.