But what if you need to do more than that? What if you need to calculate future dates from this object? How do you display your date as a relative time like ‘4 hours ago’ or ‘3 weeks ago’. How do you compare two different Date objects? You could start down a long road toward building your own library of utility methods to answer some of these questions or … Enter moment.js.
Moment.js is a very small script (5k minified) that let’s you work with dates in a very logical way using a syntax that’s easy to read. This takes all of the guesswork out of Date manipulation.
With moment.js, you can use a declarative set of methods to describe your business rule clearly.
var record = nlapiLoadRecord('invoice', 12345); var transactionDate = record.getFieldValue('trandate'); var revRecStartDate = moment(transactionDate).add('months',2).startOf('month').format('MM/DD/YYYY'); var revRecEndDate = moment(revRecStartDate).add('months',24).startOf('month').subtract('days',1).format('MM/DD/YYYY');
In this example, we retrieve the transaction date from the current invoice. Then, using moment.js, I start with the transaction date, add 2 months, go to the first of the month. For the end date, I begin with the start date, add 24 months, go to the first of the month, then subtract 1 day (without the last step, revenue recognition would include an extra month).
This is much more clear about what we’re trying to do. It’s easy to read when you come back to this code months later. We don’t have to worry about long and short months, leap years or estimations of any kind.
Some of the other things you can do with moment.js:
- .fromNow() or .fromX() to display dates in a ‘3 hours ago’ format.
- .local() or .utc() to switch back and forth between local and UTC dates.
- .calendar() to display dates as ‘Last Monday’ or ‘Tomorrow’.
- .diff() to get the difference between two moment() objects.
- .isBefore(), isAfter(), isSame() to compare moment() objects.
The list goes on. You can read all of the great documentation here. You can download the file directly or add it as a NuGet package with: