Build a Date Time Calculator Using Moment.js Library in Vanilla Javascript Full Project For Beginners

Build a Date Time Calculator Using Moment.js Library in Vanilla Javascript Full Project For Beginners


Welcome folks today in this blog post we will be building a date time calculator using moment.js library in javascript. All the full source code of the application is given below.



Get Started



In order to get started you need to make an index.html file and copy paste the following code




<label for="start">Start Date:</label>
<input id="start" name="start" type="date" placeholder="yyyy-mm-dd">

<label for="end">End Date:</label>
<input id="end" name="end" type="date" placeholder="yyyy-mm-dd">

<button type="button" onclick="calculateInterval()">Calculate Interval</button>

<p><label id="out1"></label></p>

<p><label id="out2"></label></p>

<br />
<br />
<br />
<hr />
<p>If you find this demo useful, please consider <a href="" target="_blank">donating $1 dollar</a> for a coffee or purchasing one of my songs from <a href="" target="_blank"></a> or <a href="" target="_blank"></a> for only 0.99 cents each. I have also released CDs with my band <a href="" target="_blank">Ivory Knight</a> and Annihilator main-man Jeff Waters.</p>
<p>Rob uses and recommends <a href="" target="_blank">MochaHost</a>, which provides Web Hosting for as low as $1.95 per month, as well as unlimited emails and disk space!</p>
<script src=""></script>


See also  Node.js Passport Google Authentication Using Express Full Project For Beginners


And now you need to make a script.js file and copy paste the following code




Date.getFormattedDateDiff = function(date1, date2) {
  var b = moment(date1),
      a = moment(date2),
      intervals = ['years','months','weeks','days'],
      out = [];

  for(var i=0; i<intervals.length; i++){
      var diff = a.diff(b, intervals[i]);
      b.add(diff, intervals[i]);
      out.push(diff + ' ' + intervals[i]);
  return out.join(', ');

function calculateInterval() {
   var start = new Date(document.getElementById('start').value),
       end   = new Date(document.getElementById('end').value);
     = 'Time elapsed between "' + start.toISOString().split('T')[0]
     + '" and "' + end.toISOString().split('T')[0] + '":<br/>' 
     + Date.getFormattedDateDiff(start, end);

var today   = new Date(),
    newYear = new Date(today.getFullYear(), 0, 1),
    y2k     = new Date(2000, 0, 1);

  = 'Time since New Year:<br/>' + Date.getFormattedDateDiff(newYear, today)
  + '<p>Time since Y2K:<br/>' + Date.getFormattedDateDiff(y2k, today) + '</p>';


See also  jsPDF Tutorial to Find PDF Document Page Size Pixels in Browser Using Javascript Full Project For Beginners


And now if you open index.html file you will see the below screenshot


Leave a Reply