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:
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!
momentjs. If you liked the post, please let us know how can we improve. Thanks for reading.