moment.js
is a library for manipulating dates and times in JavaScript. Since programming basically anything to do with dates and times is a pain (due to time zones, localization information, etc), using a well-established library like moment.js is essential.
As with any framework, it is important to read the documentation. In this case, it is especially crucial because if you assume (like I did) certain things, you will be scratching your head wondering what dark and evil thing has destroyed your timestamps.
Take care not to mutilate your dates
I’m used to the C# DateTime class, which has a bunch of nifty methods that will let you take an existing DateTime and give you a new one:
[code language=”csharp”]
// February 12, 1988 at 5:30 AM
DateTime RobertBirthday = new DateTime(1988, 2, 12, 5, 30, 0);
// February 12, 1989 at 5:30 AM
DateTime RobertFirstBirthday = RobertBirthday.AddYears(1);
Console.WriteLine($"Robert’s First Birthday: {RobertFirstBirthday}");
Console.WriteLine($"Robert’s Birthday: {RobertBirthday}");
[/code]
Produces the output:
I assumed that this would be the same way with moment.js — nope.
moment.js will mutate the original object. It is right there in the documentation, I just never saw it.
So, doing the same thing in JavaScript:
[code language=”javascript”]
var robertBirthday = moment("1988-02-12 5:30");
var robertFirstBirthday = robertBirthday.add(1, ‘y’);
console.log("Robert’s First Birthday: " + robertFirstBirthday.format());
console.log("Robert’s Birthday: " + robertBirthday.format());
[/code]
Produces the output:
Robert's First Birthday: 1989-02-12T05:30:00-06:00 Robert's Birthday: 1989-02-12T05:30:00-06:00
We totally got a new moment object, robertFirstBirthday, but it is pointing to the same object as our original one, robertBirthday, because moment.js mutates the object.
You can get around this by either wrapping it in moment() or using the clone() method.
[code language=”javascript”]
var robertFirstBirthday = moment(robertBirthday).add(1, ‘y’);
// —
var robertFirstBirthday = robertBirthday.clone().add(1, ‘y’);
[/code]
Robert's First Birthday: 1989-02-12T05:30:00-06:00 Robert's Birthday: 1988-02-12T05:30:00-06:00
I love moment.js. I used to hate it, but then I remembered to RTFM, and now everything is back to the way it should be.