Moment.js Javascript Date Time Manipulation Library Full Crash Course with Practical Examples

You are currently viewing Moment.js Javascript Date Time Manipulation Library Full Crash Course with Practical Examples


Welcome folks today in this blog post we will be talking about moment.js which is a date time manipulation library written in javascript. We will be talking in detail with practical examples about this library. All the source code of examples will be given below. Let’s get Started



Get Started



In order to get started you need to visit the official site of moment.js and download the library files and install it inside your root directory or you can include it from the cdn



Moment.js CDN



You can also get started by adding the moment.js library by including a CDN inside your html page and then you can use moment inside your javascript.






Installing it By NPM



You can also use moment library inside your node.js application. You just need to execute the below command to install moment as a node dependency


npm i moment



Basic Example



Now to use the moment library and have a basic example of initializing a new date in moment






Now you can see that in moment we have initialized a date and this has a special method fromNow() which returns the current time


Adding Days to Current Time


Now we will look at a example where we will add days to the current date and time in moment.js





In same way we can add minutes hours years and seconds to the current date and time in moment




Subtracting Days From Current Date and Time



Now we will be looking at an example where we will be subtracting days,hours,minutes and seconds from the current date and time in moment.




Difference Between Two Dates



Now in this examples we will be seeing how to calculate the difference between two dates in moment.js






So now you can see in the examples we are using the diff() method to calculate the difference or subtract two dates in moment.js



Date Comparisons



In order to compare two dates in moment.js we have some useful methods which are namely isBefore()isAfter(), and isSame()






Checking Leap Year in Moment



In order to check whether a year is leap or not we have a special method isLeapYear() in moment.js.






Date Validation



In order to validate dates inside your application in moment.js look at these examples






Node.js Example



At last we will be looking a node.js example where we will be using moment library.





Leave a Reply