Finding the number of days between 2 dates.

How do I get the number of days between two dates in JavaScript?

This tutorial teaches us to find the number of days between the two dates in JavaScript. If you are a developer, sometimes you face the scenario where you need to find the number of days between 2 dates.

For example, if you are building a software application to keep track of employees’ attendance and salary. If an employee leaves without completing the month, you need to count the number of days the employee attended in the current month to give the salary. Furthermore, there can be many scenarios like the above example.

In this tutorial, we will see the different methods to find the number of days between the two dates.

Using the Date Class

We will use the Date class in JavaScript to achieve our goal in this approach. The object of the date class, new Date(), returns the total milliseconds starting from 01 / 01 / 1970.

We will create two new date objects and initializes them with our dates. Also, we will use the getTime() method to get the time difference between two dates.

Syntax

Users can follow the below syntax to initialize the data object with the current date.

let startDate = new Date( Date ); let endDate = new Date( end_date ); startDate.getTime() – endDate.getTime() // returns time difference in milliseconds.

Parameters

  • Date − As a Date parameter, users need to pass the date in the mm / dd / yy format.

Algorithm

Users can follow the below algorithm to get the number of days between 2 dates.

  • Step 1 − Initialize two date objects. One with starting date and another with end date.
  • Step 2 − Find the time difference between start and end dates in the milliseconds using the getTime() method of the Date class.
  • Step 3 − Divide the time difference with the total milliseconds in the single day which is (1000 milliseconds *60 seconds *60 minutes *24 hours).
  • Step 4 − In the above step, we will get the fractional days. We will use the Math.floor() function get the complete days.

Example

In the below example, we have implemented the above algorithm to find the number of days between the two dates in JavaScript.

    

Finding the number of days between 2 dates.

Total number of days between the 05/ 10/ 2022 and 06 / 21 / 2022

Total number of days between the 03 / 21 / 2021 and current date. let days = document.getElementById("days"); let currentdays = document.getElementById("currentdays"); // finding difference between 2 dates. let start_Date = new Date('05/ 10/ 2022'); let end_Date = new Date('06 / 21 / 2022'); // calculating total time difference let timeDifference = start_Date.getTime() - end_Date.getTime(); let dayMilliSeconds = 1000 * 60 * 60 * 24; let totalDays = Math.abs(timeDifference / dayMilliSeconds); // it returns negative value if start date < end date totalDays = Math.floor(totalDays); // to get complete days days.innerHTML = totalDays; // finding difference between current date and other date let todaySDate = new Date(new Date().toISOString().slice(0, 10)); let currentDiff = new Date('03 / 21 / 2021') - todaySDate; totalDays = Math.abs(currentDiff / dayMilliSeconds); currentdays.innerHTML = Math.floor(totalDays);

The above output shows us difference between the current date and other date. Also, we can see the difference between two dates in the output.

Using the diff() Library Function of Moment JS

The Moment JS is the excellent library of JavaScript used to validate and manipulate the date and time in the JavaScript. We will add the CDN of the Moment JS library in the section of our HTML code to use it with the Vanilla JavaScript.

Читайте также:  Java display memory used

The Moment JS has a built-in method called diff() to calculate the number of days between the two dates.

Syntax

Users can follow the below syntax to use the diff() method of Moment JS.

let start_Date = moment([2018, 1, 29]); // add date in the yy / mm / dd format. let totalDays = end_Date.diff(start_Date, 'days');

Parameters

  • end_Date − It is a ending date.
  • Start_Date − It is a starting date.
  • days − To get the difference between two dates in days.

Example

In the below example, we have added the CDN to use Moment JS library in the vanilla JavaScript. After that we have create two date object using the Moment class and apply the diff() method to the dates.

      

Finding the number of days between 2 dates.

Total number of days between the 29/ 01 / 2018 and 08 / 04 / 2022 using Moment Js

In the above output, users can see it shows number of days between two dates.

Conclusion

In this tutorial, we have seen two methods to find the number of days between two. There can be many methods available to achieve our goal. In the first method, we have used pure JavaScript, and in the second method, we have used the Moment JS library method. The second method is the best approach as users don’t need to write too much code.

Источник

Javascript count days in javascript

The last step is to call the Date.getDate method.

Copied!
console.log(new Date(2025, 1, 0).getDate()); // 👉️ 31 console.log(new Date(2025, 2, 0).getDate()); // 👉️ 28

The method returns an integer from 1 to 31 , which represents the day of the month for a given date according to local time.

Getting the integer representation of the last day of the month is the equivalent of getting the number of days in the month.

Читайте также:  Java return super class

# Get the Number of Days in the Current Month in JavaScript

To get the number of days in the current month:

  1. Use the new Date() constructor to get a date object that corresponds to the last day of the current month.
  2. Call the getDate() method to get an integer representing the last day of the month.
Copied!
function getDaysInCurrentMonth() const date = new Date(); return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); > const result = getDaysInCurrentMonth(); console.log(result); // 👉️ 31

We passed the following 3 arguments to the new Date() constructor:

  1. The current year.
  2. The current month index. Month indexes are zero-based so 0 is January and 11 is December. This is why we added 1 to the result.
  3. The day for which to create a date object. When 0 is used as the day, we get back the last day of the previous month. We use this approach to balance out the zero-based month index.

It’s quite confusing but the getMonth() method returns a zero-based index.

Copied!
const date = new Date('January 04, 2025 05:24:07'); console.log(date.getMonth()); // 👉️ 0

To balance this out, we passed 0 to the days parameter of the new Date() constructor to get the last day of the prior month.

For example, passing a month index of 2 , gives us the last day of February and not March.

Copied!
console.log(new Date(2025, 1, 0)); // 👉️ Fri January 31 2025 console.log(new Date(2025, 2, 0)); // 👉️ Fri Feb 28 2025

In the function, the new Date() constructor returns an object representing the last day of the current month.

The last step is to call the Date.getDate method.

Copied!
function getDaysInCurrentMonth() const date = new Date(); return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); > const result = getDaysInCurrentMonth(); console.log(result); // 👉️ 31

The method returns an integer (from 1 to 31 ) that represents the day of the month for a given date.

Getting the integer representation of the last day of the current month is the equivalent of getting the number of days in the month.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to count the number of days between two dates in JavaScript code?

There are times when you are coding an app, you are required to count the number of days between two specific dates. For example, you are creating an application for a library and in that app, you have to calculate the number of days when someone returns a book or when a member’s subscription is required to be renewed, or when a new event comes up.

In JavaScript, to calculate the number of days between two dates we can use the date object hence let us start our article by defining what a date object is in JavaScript.

What is a Date Object

Date object is a built-in JavaScript method that allows us to work with dates and times and is initialized with the keyword new. An example of initializing a date object is given below:

The new Date() will create an object that will have the current date and time:

It’s also worth noting that the Date object just represents the amount of milliseconds from January 1, 1970.

Count Number of days between two dates

Now that we know what date the object is, let us go through an example where we will count the number of days between two Dates. For this purpose, we will first define a function with the name of getDays() and pass two arguments to this function i-e a starting date and an ending date as strings. Then in this function, we will perform other operations to calculate the number of days between the starting and ending days:

function getDays ( start , last ) {
//initialize dates with Date object
const date1 = new Date ( start ) ;
const date2 = new Date ( last ) ;

// calculation for converting a day into milliseconds
const oneDay = 1000 * 60 * 60 * 24 ;

// calculation for the time difference between start and last
const diffTime = date2. getTime ( ) — date1. getTime ( ) ;

// calculation for the days between start and last
const diffDays = Math . round ( diffTime / oneDay ) ;
// return number of days
return diffDays ;
}
const myDate = new Date ( ) ; // current time that is 10/26/2021
console. log ( getDays ( «2/1/2021» , «3/1/2021» ) ) ; // 28
console. log ( getDays ( «10/24/2021» , myDate ) ) ; // 3

In the above code, inside the getDays() function we are first declaring two dates using the arguments passed in the getDays() function. After that, we are calculating milliseconds for one day and then the difference in time between the two days. Finally, we are calculating the number of days between the two dates, storing the value in diffDays, and in the end, we return the diffDays variable. Outside the function, we initialized a Date object which will store the current date and time and then we called the getDays() function inside the console log by giving the getDays() two date arguments as strings. We also call the getDays() function with a random date and myDate arguments. The result is as follow:

Conclusion

Counting the number of days between two dates in JavaScript is a good practice program for a new JavaScript developer. Creating a program that calculates the number of days between two dates is very helpful in applications where you have to calculate the number of days and also it helps in getting acquainted with the Date object of javascript.

In this post, we first taught you what a date object is in JavaScript, and then we went on and told you how to count the number of days between two dates in JavaScript using the Date object.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.

Источник

Оцените статью