Getting started with Moment.js Managing Date and Time

It is often hard to manage Date and Time representation in web applications, but with Moment.js you can manage those stuffs in an easier and effective way. Parsing DateTime in various ways, Manipulating the DateTime to the applications needs, formatting and displaying the DateTime as required, Adding & Subtracting the Date and Time values are some of the things that can be achieved easily using Moment

Setup

You can use moment in both Web applications and NodeJs apps. To include moment in your web project download and include the moment.js script file in your code.

In all the code snippets shown here a print() method will be used to print output to a div element.

/**
* Append the given string in the output
*/
function print(str) {
  var output = document.getElementById('output');
  output.innerHTML += "<br/>" + str;
}

Parsing

In Moment there are different ways to parse and set the date and time. Once you have created a moment instance, by setting the date, then you can do lot's of stuff with that moment instance.

String + Format(s)

To get the current date and time just call moment() without params. You can also set custom date by calling the moment() method and passing the Date String and the Date Format.

/** String + Format */
// Method Signature
moment(String, FormatString);

// Usage
moment("12-23-2013", "MM-DD-YYYY");
moment("26/04/2013", "DD/MM/YYYY");

// Example
var date;
date = moment("12-23-2013", "MM-DD-YYYY");
print('Parsed date format #1 - ' + date.format("MM-DD-YYYY"));
date = moment("26/04/2013", "DD/MM/YYYY");
print('Parsed date format #2 - ' + date.format("DD/MM/YYYY"));

Note: Use this fiddle setup to test all the Example code present in this post.

The parsing tokens(YYYY, MM, DD) used here are similar to the ones used in the format method of moment, which will discussed later.

Moment is a wrapper around the default Date object. If you try to print the return value of moment it would be the UTC timestamp. To print the date in a readable way you must use the format method.

You can pass as a third parameter a boolean value to this method for the string pattern to be strict, since moment will not consider non-numeric values(-, /) while parsing.

// Will pass
date = moment("12/23/2013", "MM-DD-YYYY");

// Will fail, invalid date.
date = moment("12/23/2013", "MM-DD-YYYY", true);

An array of date formats can be passed as a second param if you know the date string could be in any one of the submitted formats.

/** String + Formats */
// Method Signature
moment(String, String[]);

// Usage
moment("12-06-2012", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]);

// Example
print(moment("12-23-2012", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]).format("DD/MM/YYYY"));

Object

You can pass to moment an object containing the information about the date and time that is to be set.

/** Creating moment by passing object */
// Method Signature
moment(Object);

// Usage
moment({ hour:15, minute:10 });
moment({ y    :2010, M     :3, d   :5, h    :15, m      :10});
moment({ year :2010, month :3, day :5, hour :15, minute :10, second :3, millisecond :123});

// Example
print("Date created using Object - " +
  moment({ year :2010, month :3, day :5, hour :15, minute :10, second :3, millisecond :123})
  .format("DD-MM-YYYY")
);

Unix Timestamp

To create a moment from the unix timestamp, use the moment.unix(timestampString) method. This might come in handy when you have stored the timestamp of a record in your database and want to display the date from that timestamp value to the user.

/** From Timestamp */
// Method Signature
moment.unix(timestampString);

// Usage
moment.unix(1442730948);

// Example
print("Date from timestamp - " + moment.unix(1442730948).format("DD-MM-YYYY"));

Cloning

You can clone your moment object to create another moment instance, since moment is mutable. To create a clone, you can either pass the moment instance into a moment(moment) method or you could use the momentInstance.clone() method.

/** Moment Clone */
// Example
var momentOne = moment();

// Creating clone with moment()
var momentTwo = moment(momentOne);

// Creating clone with moment.clone()
var momentThree = momentTwo.clone();

UTC

By default the moment methods will parse in local time, to create a UTC DateTime use the moment.utc() method. You can use the utc method in all the ways we used moment method to create the date. When using UTC, all the display methods will show the date in UTC format.

/** UTC */
// Method Signature
moment.utc()

// Example
var dateUTC = moment.utc();
print("UTC DateTime - " + dateUTC.format("MM-DD-YYYY hh:mm:ss"));
var date = moment.utc("12-23-2013", "MM-DD-YYYY");
print("Custom Date in UTC - " + date.format("MM-DD-YYYY hh:mm:ss"));

isValid

You can use the moment.isValid() method to check if moment considers the parsed date a valid date and the moment.invalidAt() method to check where the DateTime is wrong and returns the position where it is wrong.

/** Validation */
var invalidDate = moment("2015-25-11 09:90:00");

// Checks if the date is valid
print("isValid date - " + invalidDate.isValid());

// Shows where the date is invalid
print("Date is invalid at - " + invalidDate.invalidAt());

The return value of invalidAt specifies where the date is wrong with the return value representing 0 - year, 1 - months and so on to 6 - milliseconds.

Getters and Setters

Moment provides methods that can used to set values such as millisecond(s), second(s), minute(s), date(s) and so on. These methods follow a pattern similar to jQuery, where if you pass the value it will set it and if nothing is passed it will return the value.

/** Getters and Setter */
// Method Signature
moment.date() // will get the date
moment.date(Number) // Will set the date

// Usage
moment.date()
moment.date(23)

// Example
var date = moment("12-23-2013", "MM-DD-YYYY");
print("Date is - " + date.date());
print("Value after setting the date - " + date.date(02).format("DD-MM-YYYY"));

The above example shows the getter and setter only for date, but moment provides them for all other properties of date and time, like millisecond, second, day of week, year, ISO day of week, ISO week of year etc.

Moment also provides generic get and set methods.

// Usage
// Generic get method.
moment().get('month'); // 0 - 11
// Generic set method.
moment().set('month', 6);

Maximum & Minimum

To find the maximum and minimum of two moment instances you can use these methods.

  • moment.max(a, b) - Returns the one which has the most distant future i.e far from the other.
  • moment.min(a, b) - Returns the one which has the most distant past i.e behind from the other.

Manipulating

Once you have created a moment you can use various helper methods to manipulate it.

For example, you can use methods like add() and subtract() to add and subtract some unit from the moment.

/** Manipulating the date and time */
var date = moment("01-01-2013", "MM-DD-YYYY");
print("Before Manipulation - " + date.format("DD-MM-YYYY"));

date // you can chain methods
   .add(10, 'days') // add 10 days
   .subtract(2, "d") // subtract 2 days
   .year(2010); // set the year as 2010

print("After Manipulation - " + date.format("DD-MM-YYYY"));

You can chain methods in moment which will visually show how the date is being manipulated.

Other manipulation methods include startOf() and endOf(), which can be used to set the start of either year, month, week, hour etc and the other method does the opposite of it..

/** StartOf and endOf */
// Method Signature
moment.startOf(String);
moment.endOf(String);
// Example
var date = moment("05-10-2013", "DD-MM-YYYY");
print(date.isValid());
print("Start of Month - " + date.startOf("month").format("DD-MM-YYYY hh:mm:ss"));
print("End of Month - " + date.endOf("month").format("DD-MM-YYYY hh:mm:ss"));

Display

To display the date created by moment we use format() method. This method has been used in all the methods shown above to display the date and time. View the list of tokens supported by format.

Other display function that we are interested in is the time* methods. These methods can be used to display the relative time.

For example,

var a = moment("05-10-2013", "DD-MM-YYYY");
var b = moment("10-12-2015", "DD-MM-YYYY");
print(a.from(b));
print(a.to(b));
// Pass true if the suffix text is needed
print(a.fromNow(true));
// Pass true if the prefix text is needed
print(a.toNow());

These method are very useful to display date and time in your web project. There also other methods available to that can be helpful.

Query

Moment provides a set of is* methods that provide various ways to query and check the date values. Methods such as isBetween(dateString, dateString) can be used to check if a moment instance date is between the dates provided to the method. Below is a list of method examples that can be helpful.

/** Query methods */
// Check's if the date is before the date given to isBefore
print(moment("2013-01-01").isBefore("2014-01-01"));

// Check's the opposite of isBefore
print(moment("2014-01-01").isAfter("2013-01-01"));

// Check's if the date is isBetween the passed dates
print(moment("2014-01-20").isBetween("2014-01-01", "2014-01-25"));

// Check if a given year is leap year.
print(moment("2000").isLeapYear());

// Check if a variable is a moment object
print(moment.isMoment(moment()));

Moment also provides lot’s of other useful methods for each section mentioned above, check out the moment docs for more info and to learn about durations, utilities and plugins.