moment.js

Introduction to moment.js

Jan 23, 2017

Moment.js is a date library for Javascript. It has great features and is easy to use especially for those who are used to Python datetime objects. You can download it from momentjs.com or directly import cdnjs link:

https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js

Although it has many attributes, I believe its documentation is a bit complicated. I will try to explain the features that were useful for me recently.

Basic Commands

First, let’s get started by defining a moment object, now. It gets current date and time.

var now = moment();

You can also define a moment object with Unix timestamp, either in milliseconds:

var date = moment(1318781876721) // in milliseconds

or in seconds:

var date = moment.unix(1318781876) // in seconds
var date = moment.unix(1318781876.721) // specify milliseconds in seconds

You can extract the number of day in week, starting from Sunday.

moment().day() // returns integer from 0 to 6, with Sunday equals 0

Also you can get the number of weekday depending on your locale, with either first day of the week is Sunday or Monday. The first day has the value 0 and the last one gets 6.

moment().weekday()

To set a specific day around today, use an argument in .day() as follows:

moment().day(1) // represents tomorrow with the exact time of now
moment().day(-7) // represents this day a week ago

Or you can set a specific hour from a moment object:

moment().hour(9).minute(30).second(0) // returns the moment of today at 09:30AM

To add or subtract to/from a date:

var now = moment();
now.add(1, 'days'); // returns tomorrow with the exact time of now
now.subtract(1, 'weeks'); // returns last week with the exact time of now

Comparing Dates & Times

When I used moment.js, I needed to compare two or more moments. For this kind of purposes, you can use these.

Difference:

var a = moment();
var b = moment().day(1);

b.diff(a); // returns 86400000, the number of milliseconds in 24 hours
b.diff(a, 'days'); // returns 1

Time to a date, in string format:

a.to(b); // returns "in a day"

Durations:

delta = moment.duration( b.diff(a) ); // returns a duration of 24 hours length

and for a duration of 1 day, 3 hours and 5 minutes, you can display it as follows:

delta.days(); // returns 1
delta.hours(); // returns 3
delta.minutes(); // returns 5

By using all these features, I managed to calculate the time when the stock market opens or closes, and the time left until it opens or closes for a given arbitrary time. These are only a small fraction of what moment.js is capable of, if you feel like you need more of it, please visit its documentation page. I hope these will be useful for you as well, enjoy it!