· javascript moment js

Moment.js Cheatsheet

Handling date and time in JavaScript could be a pain. I am a ruby enthusiast and one thing which I deeply love about it, is its date and time helper. They are easy to use and very intuitive. In JavaScript world, moment.js comes for the rescue. It has a lot of functionality but I somehow find its syntax a bit daunting. This post aims to provide a list of few most used methods. It shall also serve as a cheatsheet and reminder to everyone. So let’s get started.

moment js cheatsheet

The Moment

I will speak less and let the code do the talking.

// returns the current time, same as new Date()
moment()

// get moment object from string, though we should not use them as they are ambiguous.
moment("10-10-1993")
moment("01/12/2015")

// instead use, it makes sure that your dates are interpreted correctly.
moment("10-10-1993", "DD-MM-YYYY")
moment("01/12/2015", "DD/MM/YYYY")

Here is a list of few most used parsing tokens:

Token Description Example
YYYY 4 Digit Year 2016
YY 2 Digit Year 16
MMMM Full Month Name January
MMM 3 Character Month Name Jan
MM 2 Digit Month 02
M 1 or 2 Digit Month 1
DD 2 Digit Date 09
D 1 or 2 Digit Date 9
M 1 or 2 Digit Month 1
HH or H 1 or 2 Digit Hour 24hrs 23
hh or h 1 or 2 Digit Hour 12hrs 01
a or A Am/Pm PM
m or mm Minutes 59
s or ss Seconds 23

Tip: lower case tokens are used for time and upper case tokens are used for date.

Breaking The Moment

We find ourself most of the time accessing different pieces of information stored in the moment object. It can be date, hour, seconds, etc

// create the moment object
var now = moment();

// to get todays date
now.date()
now.hour()
now.minute()
now.second()

// we also have get method on moment
now.get('day') // returns day of the week
now.get('millisecond')

// get unix time
now.unix()

// I have specified the list of all possible vales you can use in get, add and subtract method in the below section.

Play the Moment

var now = moment()

// clone moment
var current = moment(now)
// change to utc
now.utc()
// validate the time object
now.isValid()

// add value to a time
// prototype: moment().add(value, scale)
now.add(3, 'hours');
now.subtract(7, 'days')

// jumping to some time
now.startOf('day')
now.endOf('month')

// possible fields to use
var possibleScales = [year, month, quarter, week, isoWeek, day, date, hour, minute, second]

// use any available token to format time as you need
now.format('hh:mm a')

moment.js methods like add and subtract mutates the object itself. This can cause an unseen bug if you are not aware!

Conclusion

Moment.js is very helpful to solve date and time related problems in javascript. It was created to be easy and powerful. With the right exposure we can get our work done easily with momentjs. If you liked the post, please let us know how can we improve. Thanks for reading.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+