aahhuhuhu
aahhuhuhu

Reputation: 493

dayjs I want to do ony numbers

Unix is passed to the argument d.
I want to use much to get only the numbers but I get an error.

error message
TypeError: Cannot read property 'match' of undefined

  const date = (d) => {
    const dayjs = require('dayjs');
    const relativeTime = require('dayjs/plugin/relativeTime');
    dayjs.extend(relativeTime);
    const now = Date.now();
    const day = dayjs(now - d).fromNow();

    console.log(day.result.match(/[0-9]*/g));
  };

Upvotes: 0

Views: 1661

Answers (1)

Halmon
Halmon

Reputation: 1077

You cannot read property 'match' of undefined because result is undefined. Taking a look at day.js documentation, it looks like dayjs().fromNow() returns a string output directly in your day const. Be careful as the number it returns is not just in days, the breakdown could be hours/months/years based on the total number of days as you can see if the Range table when you scroll down.

  const date = (d) => {
    const dayjs = require('dayjs');
    const relativeTime = require('dayjs/plugin/relativeTime');
    dayjs.extend(relativeTime);
    const now = Date.now();
    const day = dayjs(now - d).fromNow(true); //pass in true to remove the suffix 'ago'

    console.log(day.split(' ')[0]);
  };

Instead of a regex match, all we need to do is split the string by spaces and take the first element which is the number 2 days ago -> 2

Upvotes: 2

Related Questions