Click here to Skip to main content
14,640,023 members
Articles » Web Development » Client side scripting » JavaScript
Tip/Trick
Posted 24 Aug 2015

Tagged as

Stats

15K views
15 bookmarked

Moment.js (A JavaScript Library to Manipulate Dates)

Rate this:
5.00 (9 votes)
Please Sign up or sign in to vote.
5.00 (9 votes)
24 Aug 2015CPOL
This library provides a very easy way to manipulate dates and times.

Introduction

This JavaScript Library helps to work with date and time. As we know, when we work on date and time using JavaScript, we encounter many challenges. So this library ultimately saves you time and effort because it provides a rich set of functions. By using them, you can directly validate, manipulate and format date values. Since this is a light-weight library, it is very easy to use without overhead. 

Background

This library is freely available. You can use either a minified or full version of this library as you require. In this library, all the operations are performed on a moment object so the date or time is stored in this library as a moment object only. So this moment object is the core of this entire library. You can find this library at Moment.js site's home page.

Using the Code

You can use this library with node.js or a browser. To use this library in Node.js, you can write the following:

npm install moment

var moment =require ('moment');
Moment.format();

And if you want to use this library, then you need to add this Moment.js library as in the following:

<script src="moment.js" temp_src="moment.js"></script>
<script>
moment().format();
</script>
  1. If you want to get today's date or time:
    var now=moment();
  2. If you want to pass a date as a string:
    var dt=moment("Dec 25, 1995");
  3. Validate a date using isValid():
    moment('122-22-2222').isVaid()
  4. When passing a date as a string if you know the format, then you can specify the format:
    moment("11-21-2013", "MM-DD-YYYY");

    We can specify the format from the table below:

    M.MM MonthNumber (1-12)
    D,DD Dayof month
    YY 2digit year
    m,mm minutes
    h,hh 24hour time
    s,ss Seconds
    S Deciseconds
    SS CentiSeconds
    SSS Milliseconds
  5. If you want to wrap a date object to moment:
    var dat = new Date(2013, 10, 22);
    var wrap = moment(dat);
  6. Fetch Date and time from a moment object:
    moment().date();
    moment().date(Number);
    moment().days(Number | String);
    moment().days();// Number
    moment().dayOfYear(Number);
    moment().year(Number);
    moment().year();

    You can use many builtin methods to fetch all details.

  7. Difference:

    If you want to find the difference between two moments, then there are many functions provided by moment.js.

    moment().diff(Moment|String|Number|Date|Array);
    moment().diff(Moment|String|Number|Date|Array, String);
    moment().diff(Moment|String|Number|Date|Array, String, Boolean);
    • To get the difference in milliseconds:
    var first = moments([2010, 0, 29]);
    var second = moments([2013, 1, 29]);
    alert(first.diff(second));
    • To get the difference in years, days or months, you can specify one more argument:
    alert(first.diff(second,'days')); 
    alert(first.diff(second,'months')); 
    alert(first.diff(second,'years'));
    • To get a floating value, suppose in the case of years, you can pass one more argument as true then it will return the exact floating value: 
    alert(first.diff(second,'years',true));
  8. Convert to JSON

    If you want to convert moment to JSON, then you can directly use the toJSON() method:

    moment().toJSON();
  9. Manipulation
    • Add:
    moment().add('days', 7);

    In place of days, you can write months, weeks, minutes, hours, seconds, and so on.

    moment().add({days:7,months:1});

    You can use this object in literal format also.

    • Subtract
    moment().subtract(String, Number);
    moment().subtract('days', 7);
  10. Formatting
    moment().format(String);

    Here, String is format of date like following:         

    moment().format("dddd, MM Do YYYY, h:mm ");
    moment().format("ddd, hA,SS");
  11. Some important functions for comparison:
    • IsBefore

    This function will check whether the first date is earlier than the second date:

    moment().isBefore(Moment | String | Number | Date | Array, String);
    moment('2012-10-10').isBefore('2012-10-11');// true

    If you want to check which current date and time.

    moment().isBefore();

    By default, it checks by miliseconds and if you want it to be restricted to some level for comparison, then you can specify that as in the following:

    moment('2012-11-20').isBefore('2012-12-31','year'); //false
    • IsSame

    This function determines whether two dates are the same or not.

    moment().isSame(Moment | String | Number | Date | Array, String);
    moment('2013-11-10').isSame('2013-11-10');// true

    You can specify which part you need to compare as in the following:

    moment('2013-11-10').isSame('2013-10-21', 'year'); // true

    This will compare the year part of the date.

    If you do not specify a date, then it will use the current time by default:

    moment().isSame();// true

    As in the methods above, moment.js also provides the following methods:

    IsAfter() ;//check if a moment is after another moment.
    isLeapYear() : // check year is leap year or not.
    isMoment() ;//check variable is moment object or not.

    There are many other features and methods available. For more information, please refer to the documentation of moments.js.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Abhishek Kumar Goswami
Software Developer
India India
I like to code and I really enjoy to share my knowledge with all, Its my passion.

http://abhishekgoswami.com/

Comments and Discussions

 
GeneralMy vote of 5 Pin
Dan Thyer24-Aug-15 9:43
MemberDan Thyer24-Aug-15 9:43 
GeneralRe: My vote of 5 Pin
Abhishek Kumar Goswami24-Aug-15 16:56
professionalAbhishek Kumar Goswami24-Aug-15 16:56 
Thanks
Abhishek Goswami

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.