New Era: Computation of Time with Moment.js
Formatting of Time Values Fast and Simple
moment().lang("de"); moment().format("Do MMMM. YYYY");
In our example we change the language to German (de). The second line formats the output to the common way dates are displayed in German language. The abbreviations will not be new to you if you have used time and date functions before. We have M for month without a trailing zero, MM for month with trailing zero and MMMM for the name of the month fully written. The value Do outputs the day in the form of a value. In German language websites this would lead to the addition of a period right after the number value. In English this is entirely different. Here we add letters to the numbers like this: 1st, 2nd, 3rd and so on. I can imagine languages with even more complicated notations…
Moment.js is not limited to the formatting of the current time, but is able to format forever time value you want to process:
moment("01-31-2013, "DD-MM-YYYY").format("Do MMMM. YYYY"); // 31. Januar 2013
Moment.js is able to validate date values. It returns
false, when it find an entry that cannot be a time oder date value:
moment("01-32-2013", "MM-DD-YYYY").isValid(); // false
Calculation of Time Spans and Durations
You know, things always get tricky, when you need to calculate with time values to find a time span value or a duration. In these hopefully rare occasions you convert time values to seconds, add or subtract two values and convert it back into a human readable format. Moment.js takes all of the pain out of this procedure and flawlessly executes it for you.
moment().add("days", 7).add("months", 1);
In this example we add seven days and one month to the current date. The result is formatted using
format() afterwards. Of course you can as well
If you need to display time values in relation to the current time, probably to show when something will happen or has happened, Moment.js provides you with the function
Depending on how far back in history the calculated date lies, Moment.js displays the values in years, months, days, hours or minutes. Instead of simply showing the plain date value, Moment.js displays values as “three days ago” or “yesterday”.
humanizeDuration() displays fixed time spans in common notation:
moment.humanizeDuration(-1, "minutes", true); // one minute ago
Conclusion: Moment.js makes computation of times dead-simple. It is a full-fledged solution where the limits in your head are reached far earlier than the limits of the tool. This way you should never really run into trouble. Choose Moment.js for your everyday needs. As it can be used under the regulations of the MIT license, you need not think twice about it.
Denis works as a freelance web designer since 2005.