It's an old question and apologies for shameless self promotion as this is not my intention, just hope it will help someone.
In addition to what razorbeard says (.clone()
etc) I created NPM module that attaches immutable methods to whatever Moment.js comes with out of the box. The intention is not to break existing code so module adds new methods with Immu
appended to its name.
Each instance returned by moment factory will be decorated with immutable methods e.g moment().startOf()
will have corresponding startOfImmu()
, add()
will have addImmu()
etc. Each of those returns new moment rather then modifying existing one. To use it just pass moment
factory to momentImmutableMethods
to get access to new immutable methods. Example:
var moment = require('moment'); // or moment-timezone
import { momentImmutableMethods } from 'moment-immutable-methods';
// to decorate instances with immutable methods we need to extend moment factory as below:
momentImmutableMethods(moment);
// now every instance returned by moment will have Immu methods attached.
// IMMUTABLE EXAMPLE
// we using immutable methods that were attached to every instance, these have Immu appended to original name
const ddd = moment({
hour: 5,
minute: 10
});
// Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…}, _locale: Locale, …}
const eee = ddd.startOfImmu('day');
// Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…}, _locale: Locale, …}
console.log(ddd === eee);
// false
const fff = eee.startOfImmu('month');
// Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…}, _locale: Locale, …}
console.log(ddd === fff);
// false
console.log(eee === fff);
// false
console.log(ddd.format('DD/MM/YY HH:mma'));
// "14/04/18 05:10am"
console.log(eee.format('DD/MM/YY HH:mma'));
// "14/04/18 00:00am"
console.log(fff.format('DD/MM/YY HH:mma'));
// "08/04/18 00:00am"
Its on NPM at https://www.npmjs.com/package/moment-immutable-methods