Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dayjs - not a function

I'm passing two dayjs date to Vars.date global variables.

var dayjs = require("dayjs") for import
   
Vars.date1 = dayjs(whateverdate1("add", 2)).format('MMM D, YYYY')
Vars.date2 = dayjs(whateverdate2("add", 2)).format('MMM D, YYYY')

const date1 = Vars.date1
const date2 = Vars.date2
let diff = date1.diff(date2, 'month')
console.log('diff' + diff)

error: TypeError: date1.diff is not a function

I am unable to use diff and get methods, always 'not a function'

What did I miss?

like image 435
arena Avatar asked Jul 26 '26 04:07

arena


2 Answers

Make sure that Day.js supports the require() function. If it is import-based, you need to maybe change the import to that.

So, just try doing the following.

import dayjs from "dayjs";

Links

  • npm Package
  • Official Day.js website
like image 87
Viradex Avatar answered Jul 29 '26 06:07

Viradex


I think you had two problems:

  1. add() should be called like dayjs().add(2, 'month')
  2. Your were trying to call diff() on a string (the output of dayjs().format()) rather than a Dayjs object

Here's how you can create two dayjs objects and find their difference in months:

const dayjs = require("dayjs")
// or:
// import dayjs from "dayjs";

const date1 = dayjs()   // Dayjs object of current month
const date2 = dayjs().add(2, "month") // Dayjs object of 2 months from now

date2.diff(date1, "month") // 2
like image 28
Ty Hitzeman Avatar answered Jul 29 '26 06:07

Ty Hitzeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!