How can I extend moment.js and add new functions/methods to it?

Viewed 464

In a React project, I'm using moment.js (version 2.22.2) and would like to extend it and add new functions to it in order to simplify common use cases.

I've tried several different ways of extending moment.js, but after lots of experimentation and Googling, I haven't been able to figure it out.

None of the following work:

#1:

import moment from 'moment';

moment.formatForDb = () => {
    return this.format('YYYY-MM-DD');
};

export default moment;

#2:

import moment from 'moment';

moment.prototype.formatForDb = () => {
    return this.format('YYYY-MM-DD');
};

export default moment;

#3:

import moment from 'moment';

moment.fn.formatForDb = () => {
    return this.format('YYYY-MM-DD');
};

export default moment;

Does anyone know how to extend moment.js so that new functions can be added to it? Thank you.

1 Answers

Many thanks to Daniel A. White and Jeremy Thille in the comments above for pointing me in the right direction.

It turns out that you do indeed need to use .fn, but the problem was that I was using an arrow function, as opposed to a standard function, for which the meaning of this is different.

As such, here's the working code:

import moment from 'moment';

moment.fn.formatForDb = function () {
    return this.format('YYYY-MM-DD');
};

export default moment;

Thanks again!

Related