Search code examples
javascriptnode.jstimedifferenceabbreviation

How can I parse time based tokens in JavaScript/Node.JS?


I am trying to currently create a Discord bot which does temporary banning and for the most part I know how to handle this. The only issue is that I can't figure out how I would use an argument like 3w/2w/1y/etc to convert to a new time to create a timer. I've crawled all over Google to find an answer and I can't find even a slight hint or tip on how to accomplish this, maybe you guys might be able to point me in the right direction.


Solution

  • I would use a regex to parse the argument, and then map it to a date via milliseconds:

    const mapping = {
      w: 7 * 24 * 60 * 60 * 1000,
      d: 24 * 60 * 60 * 1000,
      // whatever other units you want
    };
    
    const toDate = (string) => {
      const match = string.match(/(?<number>[0-9]*)(?<unit>[a-z]*)/);
      if (match) {
        const {number, unit} = match.groups;
        const offset = number * mapping[unit];
        return new Date(Date.now() + offset);
      }
    }
    

    Examples:

    > toDate('3w')
    2020-09-08T19:04:15.743Z
    > toDate('2d')
    2020-08-20T19:04:20.622Z