Moment Js – Manage Date & Time in JavaScript
In this article, we will discuss Moment Js – Manage Date & Time in Javascript. As we know, working with dates and times is not an easy task. It’s too much time consuming to write some code for dates and times again and again. Here’s a JavaScript library Moment Js which provides the rich features and fulfill all our needs related to the dates and times.
Table of Contents
Install Moment Js
It’s an open source library. It is designed to work both in the browser and in Node.js. In order to use in this our project, we need to add the moment.js in the head tag.
<script src="assets/js/moment.js"></script>
In Node.js project, we can use the given command to install moment js.
npm install moment
Formatting Date
moment.js provides format() function which helps us to set the required date format with specific parameters. For example:
moment().format('DD-MM-YYYY')
Here’s the working demo:
Validate Date
moment.js provides an easy way to validate the date. As we know, we need date validation in lots of time. With the help of moment.js, we can validate the date easily and in less time.
$('#submit').click(function(){ var dateEntered = $('#cDate').val(); if(!moment(dateEntered,'MM-DD-YYYY').isValid()){ $('#msg').addClass('error').text('Invalid Date (Accepted format MM-DD-YYYY)'); } else { $('#msg').addClass('success').text('Valid Date'); } });
You can get an idea of how date validation works with the help of given working example.
Add / Subtract Dates
Adding or Subtracting days, months or years in the date is a time-consuming task. Write no of line code to achieve the requirement. But with the use of moment js, it’s easy and simple to adding or subtracting days from any date.
Add Days / Months / Years
moment().add('days', 3); // adds 3 days to current date moment().add('months', 3); // adds 3 months to current date moment().add('years', 3); // adds 3 years to current date
Subtract Days / Months / Years
moment().subtract('days', 3); // subtracts 3 days to current date moment().subtract('months', 3); // subtracts 3 months to current date moment().subtract('years', 3); // subtracts 3 years to current date
Here’s the working example, you can see how addition and subtraction works.
Conclusion
Moment Js is a wonderful library, which offers rich feature related to date/time manipulation, validations and etc. Also, Moment Js offers support for the international language. In this article, we try to explain some of the basic features of Moment Js. You can check the official plugin page for more details. No doubt, Moment Js simplifies the job of developers. Also, feel free to add the comment if any query. You can found more tutorials here.
If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee