Jimmy Breck-McKye Jimmy Breck-McKye - 1 year ago 113
Javascript Question

How can I set the Unix epoch of a moment js object?

I have a moment.js object whose Unix epoch value I'd like to change.

Normally I'd use

myMoment = moment(someEpoch);
, but because of design constraints I'm having to pass the object by reference, so I must mutate the value rather than replacing it altogether.

What is the neatest and (ideally) most performant way to do this in v2.15+?

Answer Source

Assuming m is a moment object, and t is the timestamp to set (in ms), probably the easiest way is:


Or if you prefer to be more verbose:

m.add(t - m.valueOf(), 'ms');

Note that the default units are milliseconds when not specified and the input is numeric. If your input timestamp is in whole seconds, you'd have to multiply it by 1000 in either of the above formulas before subtracting the value of m.

However, if you're really after the most efficient code in terms of minimizing total operations performed internally, you could modify moment internals directly. Doing so is dangerous in that there's no guarantee the internals won't change between versions. Only the public API compatibility is guaranteed, following SemVer rules. So only do this if you are optimizing for perf and are willing to deal with potentially breaking changes in the future:

m._d.setTime(t + ((m._offset || 0) * 60000));

This is essentially an inversion of moment's valueOf function, and is probably what the implementation would look like if it were built in to moment.

Of course, if you are only working with moments in UTC mode, you can just do:


One last thing, with regard to terminology, you can't actually set "the Unix epoch value", because the epoch is a fixed value. In this context, "epoch" means the timestamp that is zero, which is associated with 1970-01-01T00:00:00.000Z. It cannot be changed. You are simply using a "Unix Timestamp in milliseconds", or perhaps an "epoch-based timestamp". But it is a misnomer for your variable to be named someEpoch.