Search code examples
javascriptdayjs

Dayjs return number instead of relative word with `.form`


There are plugin on dayjs (relativeTime) that will returning human readable string instead of number. Is there any way to return just number?

something like these

dayjs('2020-07-1').from(dayjs('2020-07-9')) // -8
dayjs('2020-07-1').from(dayjs('2020-07-1')) // 0
dayjs('2020-07-11').from(dayjs('2020-07-9')) // 2 

Solution

  • Working Code !!

    Using diff() method from dayjs library with 'day' as a second parameter

    console.log(dayjs('2020-07-1').diff('2020-07-9', 'day'));     // -8
    console.log(dayjs('2020-07-1').diff('2020-07-1', 'day'));     // 0
    console.log(dayjs('2020-07-11').diff('2020-07-9', 'day'));    // 2
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.29/dayjs.min.js" integrity="sha512-APVsMirhHF2o3YdCSwYonM7egfT589pTqyoy5hIzEbs9sAGJSbEI6ssXUwngHjaq4V/GmmmpgqrcLSvsO+gsJQ==" crossorigin="anonymous"></script>

    NOTE: 'day' can be replaced with 'd' which being a shorthand