JAVA SCRIPT - Finding the Number of Days Between Two Dates - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Finding the Number of Days Between Two Dates - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, January 2, 2019

JAVA SCRIPT - Finding the Number of Days Between Two Dates

 Finding the Number of Days Between Two Dates


Problem

You can create two different dates with the Date object, but you can’t easily find the number of days between them.

Solution

Use the date library Moment.js to access the more advanced datetime functions. The following solution shows how to find the number of days between two dates using this library:


var deadline = moment('October 1, 2014');
var t = moment();
var df = deadline.diff(t, 'days');
console.log(df); // 37 days

EXPLAIN

The Moment.js library can be used in Node via npm, or in the browser—either down‐ loaded, via Bower or Require.js, or linking directly to the CDN:

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.1/moment.min.js">
</script>

The Date object does not provide any technique to easily find differences between two dates. Not so with Moment.js. In the solution, I could easily discover how many days there were between two dates. And in the following snippet, I created a Date when this was written, and added seven days:

var t = moment();
console.log(t.format("dddd, MMMM Do YYYY, h:mm:ss a")); // formatted date
t.add(7, 'days');
console.log(t.format("dddd, MMMM Do YYYY, h:mm:ss a")); // date 7 days in future

The Moment.js library is an excellent example of a small, well-purposed JavaScript li‐ brary fulfilling a real need.

No comments:

Post a Comment

Post Top Ad