Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple moment plugins?

I know I have to import the moment plugin if I want to use it. Like this:

import * as moment from "moment-timezone";

//here I can use moment.tr.names() etc.

But what if I want to use multiple plugins? I know that plugins in moment import moment, add their functionality and then export moment again. But if that's correct, how do I use multiple plugins?

One option is to import them under a different name like:

import * as momentJdate from "moment-jdateformatparser";
import * as momentTimezone from "moment-timezone";

Or I can merge them into one moment object like this (using deepExtend):

let moment = {};
deepExtend(moment, momentJdate, momentTimezone);

//here you should be able to use moment().toJDFString() and moment.tz.names()

But neither of those seem to be clean code. Is there a better way to do this?

like image 303
Spitzbueb Avatar asked Sep 07 '17 08:09

Spitzbueb


People also ask

Is MomentJs deprecated?

MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week.

How do you add one day in a moment?

This is a pretty robust function for adding time to an existing moment. To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');

How do you compare dates with moments?

Compare two dates using Moment.js has a diff() method, which gives the difference between two dates in years, months, days, hours, minutes, seconds, milliseconds, etc. We can use the second unit in our case to find the difference between the two dates. Before using the Moment. js methods, make sure to include Moment.

How do you use moments?

moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day.


1 Answers

What works for me and I think is clean-ish to import one after the other. For example:

moment = require('moment-business-days');
moment = require('moment-timezone');
moment().tz('America/New_York').businessAdd(1).startOf('day').add(7, 'hours')

It is not ideal, because it is opaque and without understanding how node works you might think the first require is pointless. But it is clean and effective.

like image 120
fsaint Avatar answered Sep 28 '22 06:09

fsaint