Working with dates and times is always a bit complicated, like how we manipulate time, time validation, and more. In javascript we can use MomenJS which is a Javascript library that specifically handles date and time.
With MomenJS, we no longer need to think about manipulation or anything related to date and time. Okay, first stage first download MomenJS library at http://momentjs.com/
Or by using the node, install the module using the command
Format Dates
We will do the time manipulation with MomentJS, create an index.html file that calls the MomentJS library by filling in the following code:
<html>
<head>
<script src="moment.js"></script>
<script>
var currentTime = moment().format(‘YYYY MM DD’);
console.log(‘Current Time is ‘, currentTime);
</script>
</head>
<body>
</body>
</html>
To display the data, for example in this tutorial, we can use the format function(); Then run the file in browser, open Developer Tools (f12) and select console, you can see the result like picture below.
With the format () function, we can specify the format to be displayed by entering the parameters into function format (), then what if we want the format that comes out not only numbers, but with the name of month, hour, minute and second? Relax, we can enter the YYY-MMMM-DD HH: MM: DD command into the format parameter (). Type the following line :
<script>
var currentTime = moment().format(‘YYY-MMMM-DD HH:MM:DD’);
console.log(‘Current Time is ‘,currentTime);
</script>
Here we have currentTime variable that contain momentjs format function, then with console we printout the data from currentTime, you can see the result below.
In the picture above we will change it to 22 December 2017 04:12:22, we just change the form of the parameters sent into function format (), type these following code, then the format will automatically change. See the picture below.
<script>
Var currentTime = moment().format(‘DD MMMM YYYY HH:MM:DD’);
console.log(‘Current Time is ‘,currentTime);
</script>
Here we only change the format from ‘YYY-MMMM-DD HH:MM:DD’ to ‘DD-MMMM-YYYY HH:MM:DD’.
Please note HH: MM: DD if written in capital letters, it will show 24 hour format, whereas if written in lower case hh: mm: dd will display 12 hour format (PM / AM). If we just want to display the name of the day only, we can use the format command moment (). Format ('dddd') must be lowercase.
Set Language
By default the language obtained is English, we can change it into Indonesian language easily, we only need to change the language setting in MomentJS only, where MomentJS itself has supported many languages in its library.
To set the language, we simply enter the language name of the lang () parameter to be the moment.locale ('id'), where MomentJS is ready for use in Indonesian.
Time validation
Another greatness of MomentJS is the availability of the validation function isValid (), where with that function we can check the date we will check and will return true if the date is true and false if the date is false. For example, write down the code below.
<script>
var initialDate = ‘2017-12-12’;
if(!moment(initialDate, ‘MM-DD-YYYY’).isValid()){
console.log(‘your format date is wrong, please set MM-DD-YYYY’);
}else{
console.log(‘your formate date is true’);
}
</script>
Here we check the date format, where we only want the format sent with the format MM-DD-YYYY format (month - date - year), but put into the variable of the check is the year-month-month format, so the time of checking isValid function () will return the false value.
Now we replace the contents of the initialDate variable with the correct format, ie var initialDate = '12 -22-2017 ', then rerun then isValid () will return true, since the format entered in accordance with the validation format.
<script>
var initialDate = ’12-22-2017’;
if(!moment(initialDate,’MM-DD-YYYY’).isValid()){
console.log(‘your format date is wrong, please set MM-DD-YYYY’);
}else{
console.log(‘your format date is true’);
}
</script>
Because the data we input for initialDate is the same format with ‘MM-DD-YYYY’ so the result is true
Date Manipulation
In this date manipulation, we will manipulate date additions by day, month and year with add () function. And the reduction of dates can also by day, month and year with subtract function ().
Added date
To find the next 7 days from date now, we can use the add ('days', 7) command, where the first parameter of the day itself means we will add in the day form, while this second parameter means how many days we will add from the current date if we set the date. To try it, type the following code.
<script >
var next7Date = moment().add(7,’days’).format(‘DD-MMMM-YYYY’);
console.log(next7Date);
</script>
Add(7,’days’) mean we use format to get date 7 days from now (when i write this post is 22 december 2017), the result is below.
From the example above, because the current date is 22 december 2017, so if we add the next 7 days, then the date is 29 December 2017. What if we want to add the date at the time we set ourselves, not from the current date? The answer we just need to enter the date we want to add into the function (). Suppose we want to add 7 days ahead from December 25, 2017, type the following code
moment ('25 -12-2017 ',' DD-MMMM-YYYY '). add (7,' days') format ('DD-MMMM-YYYY').
What if we want to add months or years? In essence, we only need to change the parameters in the add () function if we want to add how many months ahead we enter add (1, 'month') this means 1 month ahead, while for the year we replace with add (1, 'year' ).
<script>
var nextMonthdate = moment(().add(1,’month’).format(‘DD-MMMM-YYYY’);
console.log(“Next Month : “+nextMonthdate);
var nextYeardate = moment().add(1,’year’).format(‘DD-MMMM-YYYY’);
console.log(“Next Year: “+nextYeardate);
</script>
Result from above script
Previous date
To get previous date, use the subtract () function. By default, the subtract () function is the same as add (). So the rules we discussed in the previous add () function also apply to the subtract () function. Suppose we will reduce 7 days from the current date, 1 month from the current date and 1 year from the current date.
<script>
var last7date = moment().subtract(1,’days’).format(‘DD-MMMM-YYYY’);
console.log(“last 7 Date : “+last7date);
var lastMonthdate = moment().subtract(1,’month’).format(‘DD-MMMM-YYYY’);
console.log(“Last Month : “+lastMonthdate);
var lastYeardate = moment().subtract(1,’year’).format(‘DD-MMMM-YYYY’);
console.log(“Last Year : “+lastYeardate);
</script>
Result from above script
Calculates the date difference
To calculate the difference between two dates, we can use the diff () function, with this function the difference is calculated in milliseconds by default, but we can also return it in the form of days, months and years. Type the following line of code.
<script>
var date1 = moment(‘2017-12-22’);
var date2 = moment(‘2015-12-22’);
console.log(date1.diff(date2), ‘milisecond’);
console.log(date1.diff(date2,’days’), ‘days’);
console.log(date1.diff(date2,’month’), ’month’);
console.log(date1.diff(date2,’year’), ‘year’);
</script>
In this example i make 2 variabel that contain differetn date, the using diff() function we calculate the difference. The result is below.
Time from now
To find out how much time from now, we can use the command fromNow (), for example, type the following command line, the result will be a few seconds ago.
<script>
var date1 = moment().fromNow();
console.log(date1);
</script>
Output from above script.
Date comparison
MomentJS also provides functionality to compare dates. Some of these functions are isBefore (), isAfter () and isSame (). These functions will return a boolean.
For example, type the following line of code:
<script>
var date1 = ‘2015-12-22’;
console.log(moment(date1, ‘YYYY-MM-DD’).fromNow();
</script>
Output from above script.
Conclusion
Moment.js is really an awesome library that simplifies date and time related manipulations and validations. This library simplifies the job of application developers, which is almost always a good thing. In this article, we focused on some of the features of Moment.js which help in parsing, validating, and manipulating the datetimes in the browser and Node.js applications.
Posted on Utopian.io - Rewarding Open Source Contributors
Congratulations @fahrulhidayat! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP
Nice post bro , keep on fire ... !!!
thanks bro, lets fire up ^
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
thanks for your review :)
Hey @fahrulhidayat I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x