Recently, I've been working on a project where I needed to calculate the number of days between two dates. So, I thought I should share a sample code for other developers.

Below is a quick and simple code for calculating the number of days between two dates in JavaScript. It's based on the concept that you can get the milliseconds between two dates by subtracting two date objects and then convert this result into the number of days.


<!DOCTYPE html>
<html>
<head>
    <title>DotNetPeTips-JavaScript</title>
</head>
<body>
    <script>
        var second, first;
        first = new Date("2020-05-02");
        second = new Date("2020-04-02");
        var days = Math.round((first - second) / (1000 * 60 * 60 * 24));
        document.write("<br>Difference: " + days);
    </script>
</body>
</html>

Difference between two dates in minute, hours javascript

We can also write a common logic to calculate the difference in milliseconds, days, hours, and minutes.

<script>
        var todaydate = new Date();
        //adding one to the current year
        var nextyear = todaydate.getFullYear() + 1;
        //create date object for future date
        var futuredate = new Date(nextyear + "-01-01");//which is next year newyear date
        //subtracting both date
        var milliseconds = (futuredate - todaydate); // milliseconds between now & future date which new year date
        var days = Math.floor(milliseconds / 86400000); // days
        var hours = Math.floor((milliseconds % 86400000) / 3600000); // hours
        var minutes = Math.round(((milliseconds % 86400000) % 3600000) / 60000); // minutes
        document.write("<br>" + days + " days " + hours + " hours " + minutes +" minutes until newyear");
    </script>

  • It creates a new Date object representing the current date and time (todaydate).
  • It adds 1 to the current year to get the next year (nextyear).
  • It creates a new Date object for the next New Year's Day by specifying the next year and January 1st (futuredate).
  • It calculates the difference in milliseconds between the future date and the current date and stores it in the milliseconds variable.
  • It calculates the number of days remaining by dividing the milliseconds difference by the number of milliseconds in a day (86400000) and rounding down (Math.floor(milliseconds / 86400000)).
  • It calculates the number of hours remaining by finding the remainder of dividing the milliseconds difference by the number of milliseconds in a day, then dividing that by the number of milliseconds in an hour (3600000) and rounding down (Math.floor((milliseconds % 86400000) / 3600000)).
  • It calculates the number of minutes remaining similarly by finding the remainder of dividing the milliseconds difference by the number of milliseconds in a day, then the remainder of that by the number of milliseconds in an hour, and finally dividing that by the number of milliseconds in a minute (60000) and rounding (Math.round(((milliseconds % 86400000) % 3600000) / 60000)).
  • It displays the calculated days, hours, and minutes remaining until the next New Year's Day using document.write().

Let’s consider a real-time example. Suppose I want to calculate my age in days, hours, and minutes. How can we achieve that task? Please see the code below.

<!DOCTYPE html>
<html>
<head>
    <title>AppsloveWorld-JavaScript</title>
</head>
<body>
    <script>
        var todaydate = new Date();
        //adding one to the current year
        //create date object for my dob
        var dob = new Date("1992-01-25");//my dob date in yyyy-dd-mm
        //subtracting both date
        var milliseconds = (todaydate - dob); // milliseconds between now & future date which new year date
        var dobdiffdays = Math.floor(milliseconds / 86400000); // days
        var dobdiffhours = Math.floor((milliseconds % 86400000) / 3600000); // hours
        var dobdminutes = Math.round(((milliseconds % 86400000) % 3600000) / 60000); // minutes
        document.write("<br>My Age : " + dobdiffdays + " days " + dobdiffhours + " hours " + dobdminutes + " minutes");
    </script>
    
</body>
</html>

Output

Ageoutput

Nowadays, their public date and time are shown in the articles of all the famous websites because technology is changing very fast.

That’s why it is necessary to do this and it is also useful, this is an era of change, in this, the incidents are happening fast, millions of articles are published on the internet in a day, so you have to manage these articles and show them at the right time. It is necessary to know the time and date

The date and time tell the user whether the information is old or not, for example, an article written 5 years ago from today is not necessarily useful in the present time, so it is important for you.

That the date and time should be shown to the user so that the user can decide whether the given information is useful for him or not.

JavaScript provides a date object to show you date and time-related information, along with this object you have some built-in properties and methods.

By using these properties and methods, you can perform date and time-related operations on the webpage.

There may be many other situations in which you can use date object, such as if you want to store information about the complete activity of the user, then you can do it through date object, user login time, logout time. If the user has made an update, then you can also store that time through the date object.

Creating javascript date object

The date object has to be constructed, you cannot use it directly, so a date object is created by the new keyword, you can create the date object in 4 ways.

In the first method, you create a normal date object and do not pass any value in it, whose general syntax is being given to you below.

var objectName=new Date();

In the above syntax, a normal object will be created, will show the day, date, time, and standard time zone.

In a second way, while creating the date object, you can pass milliseconds while creating the object.

var objectName=new date(milliseconds);

In a third way, while creating the date object, you can pass it as a date and time string, by doing this, the date object will show the same date and time, whose general syntax is being given below.

var objectName=new
Date("date/month/year
hour:minute:seconds”);

In a fourth way, while creating the date object, you can pass date object by separating the year, month, day, hours, minutes, second, milliseconds from the comma respectively, whose syntax is being given below.

var objectName=new date(year,month,day,hours,minutes,seconds,millisecond);

javascript date object property

Javascript provides you 2 properties with date object

constructor – this property returns the function by which the date object has been created
prototype – By this property you add your custom properties and method to the object

javascript date object method

Below are some built in methods available with the date object.
getDate()

This method returns the current day between 1 to 31, you call it with the date object, whose example is being given below.

<script type="text/javascript">
var datebj = new Date();
var dayofdateobj = datebj.getDate();
document.write("<br>dayofdateobj: " + dayofdateobj);
</script>

getDay()
This method returns the current day from 0 to 6 for example if today is Thursday then this method will return 4 whose example is being given below.

<script type="text/javascript">
var datebj = new Date();
var Day = datebj.getDay();
document.write("<br>Day: " + Day);
</script>

getFull Year()

This method returns you the year, if the date object is initialized with a string date, then this object will return the same year, otherwise the current year will be shown, example is given to you below.

<script type="text/javascript">
var datebj = new Date();
var FullYear = datebj.getFullYear();
document.write("<br>FullYear: " + FullYear);
</script>

Similarly, JavaScript provides you more methods to use with the date object, the list of all the methods is being given below.

  1. getHours()
  2. getMinutes()
  3. getSeconds()
  4. getMilliseconds()
  5. getMonth()
  6. getTime()