Displaying date/time has never been an issue but manipulating them has never been an easy task. Earlier programmers manually made the calculations but with time, analytics became important with demand for more complex calculations. To match up those modern requirements, we have moment.js. Download it from the links on the homepage and save it as moment.js
in the root folder.
As the motto says 'Parse, validate, manipulate, and display dates in javascript' , moment.js
has definitely eased up the task. It helps to make calculations and display, in a range of formats. A small step would be to start with the docs.
No great requirements, simply need to include moment.js
as shown in the docs in the index.html
.
<html>
<head>
<title>
Moment JS
</title>
<script src="moment.js"></script>
</head>
<body>
</body>
</html>
We are going to use javascript
based alert
and console.log()
to see the results. We write our first basic function to get current time and date.
<script type="text/javascript">
function basic () {
alert(moment());
}
basic();
</script>
This will give you something like this Thu Jul 17 2014 23:29:36 GMT+0530
.
Also you can put in a custom time in various other standard ISO-8601 formats listed here. Let us try 2013-02-08 09
as an argument in moment()
.
function advanced () {
alert(moment("2013-02-08 09"));
}
advanced();
Hitting this on browser will give you Fri Feb 08 2013 09:00:00 GMT+0530
. Other ISO-8601 formats may also be used.
But these formats are seldom used when the inputs comes from a user. User enterns the date in an informal way and it can become different with each user. MomentJs has the capability to deal with this as well.
It has String + Format options where the date can be parsed easily with options. Let us look at some of the examples to understand this.
function non(){
alert(moment("07-17-2014", "MM-DD-YYYY"));
}
non();
This gives the result Thu Jul 17 2014 00:00:00 GMT+0530
. Let us interchange the month and date along with changing the format to DD-MM-YYYY
.
function non(){
alert(moment("17-07-2014", "DD-MM-YYYY"));
}
non();
The result turns out to be same. This feature gives more flexibility to the developer to introduce user specific date format. Also MomentJs accepts all kinds of separators. For example, dates like 07/17/2014
are treated in the same way.
If their is unsurity in the format entered by user, multiple formats can be specified as well.
function multiple(){
alert(moment("24-07-2014", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]));
}
multiple();
This will result in MomentJs selecting the last format and the result would be Thu Jul 24 2014 00:00:00 GMT+0530
. But if an ambiguity occurs, MomentJs chooses the intiial one.
How to validate any certain MomentJs object ? Simply check it using moment().isValid()
which returns a boolean value.
Many a times it happens that a user enters a particular date or month and then it has to be converted to full Date()
object manually. Well MomentJS has a function for this which assumes other parameters to be default
if you specify one of them. Example:
moment()
- Gives current date and time.moment("10","hh")
- Will make the hour as 10. The smaller unit are made 0 and elder units are taken from current time. Hence this will make minute and seconds as 0 but month and year will retain the original value ieFri Jul 18 2014 10:00:00 GMT+0530
. Month and date might be different when you execute it on your system but hour, minute and seconds will reflect these values.moment("3","MM")
- This time we set the month instead. Hence date becomes1st March
and rest 0 ieSat Mar 01 2014 00:00:00 GMT+0530
.- Mutliple parameter can also be specified.
moment({hour: 5, minute: 10, seconds: 20})
- ShowsSat Jul 19 2014 05:10:20 GMT+0530
as output.moment("Mar 3 05:13:07", "MMM DD hh:mm:ss")
- ShowsMon Mar 03 2014 05:13:07 GMT+0530
It is rather easy to copy momentjs object. See the docs here.
var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012
Suppose a moment object is created and now various elements like days, months, year etc are to be deduced from the object. Momentjs provides simple API to it.
var a = moment("2013-02-08 09");
a.second();
a.minute();
a.day(); // gives '5' as output. Week index (0-6)
a.month(); // gives '1' as output. Month index(0-11)
a.year(); // gives '2013'
a.week(); // gives '6' (ie 6th week of the year)
More related to these methods can be found here.
Simple queries like comparing dates, checking leap year etc can be done too.
moment('2010-10-20').isBefore('2010-10-21'); //true
moment('2010-10-20').isAfter('2010-10-21'); //false
moment([2000]).isLeapYear(); //true
These are really useful operations which a web developer needs on daily basis.
With more endless functionalities which can be discussed, I think this will be an appropriate end to the matter. I hope after reading this, momentjs interests you and you can spend more time in exploring the same using the docs. There are tons of more functions and combinations of which can almost make a time machine with so many functions in its basket. So I will leave it here and proceed on to another interesting topic.