Calculate difference between 2 dates – jQuery
Demo – Calculate difference between 2 dates
Convert time to different timezones
Calculating difference between 2 dates requires 2 calendars to pick dates or you may want to calculate difference based on some database values. For example, say you have a project management site and when you create a project you also set it’s deadline too. Now you may want to know how many days are remaining till deadline, you will something like this:
$remaining_days = $deadline – $today;
So we will be using 2 different methods to calculate difference. 1st is by creating two input fields for the user to select the dates and 2nd method is by calculating difference from database datetime value.
From datetime picker
Start off by downloading the datetimepicker from the link below, you can also find this too in the source files at the end of this page:
Download datetimepicker
Download this library and place 3 files in your project:
- jquery.js
- build/jquery.datetimepicker.min.css
- build/jquery.datetimepicker.full.js
After that, include these files in your project, make sure to include jquery.js first:
<link rel="stylesheet" href="jquery.datetimepicker.min.css" />
<script src="jquery.js"></script>
<script src="jquery.datetimepicker.full.js"></script>
Now, create 2 input fields to select the dates and a button to click and calculate the difference:
<input type="text" id="date1" />
<input type="text" id="date2" />
<button onclick="calculateDifference();">Calculate</button>
First, you have to initialize both input fields to show the calendar when clicked:
<script>
$("#date1").datetimepicker({
timepicker: false,
format: "Y-m-d"
});
$("#date2").datetimepicker({
timepicker: false,
format: "Y-m-d"
});
</script>
At this point, you will be able to select 2 dates from 2 input fields. Now you have to implement the calculateDifference() inside <script> tag to actually perform the difference:
function calculateDifference() {
// Get both values from input field and convert them into Javascript Date object
var date1 = new Date($("#date1").val());
var date2 = new Date($("#date2").val());
// Difference can be calculated by subtracting the first date timestamp from second date timestamp
var timeDifference = date2.getTime() - date1.getTime();
// Just for debugging purpose
console.log(timeDifference);
}
At this point, when you click the button, you will be able to see the difference in timestamp in your browser console. You can open the browser console by right clicking in empty area and select “Inspect element”. The 2nd tab should be named “Console”.
Now you have to convert this timestamp in days. As the timestamp is in milliseconds, you first have to convert them in seconds, then in hours, then finally in days.
// There are 1000 milliseconds in 1 second
var milliSecondsInOneSecond = 1000;
// There are 3600 seconds in 1 hour
var secondsInOneHour = 3600;
// And we all know there are 24 hours in 1 day
var hoursInOneDay = 24;
We have to divide this timestamp by the product of these 3 variables:
var days = timeDifference / (milliSecondsInOneSecond * secondsInOneHour * hoursInOneDay);
console.log(days);
If you check your browser console now, you will be able to view the difference of your 2 selected dates in days.
From database MySQL value
We are using a sample database called classicmodels
, it will be included in the source files at the end of this page. We have a table called orders
and 2 columns requiredDate
and shippedDate
. Subtracting shipped date from required date to know how many days it will take to send the product.
$days = $requiredDate – $shippedDate;
First we have to connect with database and get the record:
<?php
$connection = mysqli_connect("localhost", "root", "", "classicmodels");
$sql = "SELECT * FROM orders WHERE orderNumber = '10100'";
$result = mysqli_query($connection, $sql);
$row = mysqli_fetch_object($result);
?>
Now you have to convert these 2 datetime values in timestamp by using the PHP built-in function strtotime(). Then you can apply the same formula as above to convert milliseconds to days.
// Converting both values in timestamp milliseconds
$date1 = strtotime($row->shippedDate);
$date2 = strtotime($row->requiredDate);
// Calculating the difference in milliseconds
$date_difference = $date2 - $date1;
// Converting milliseconds into days
$days = round($date_difference / (60 * 60 * 24));
echo $days;
[wpdm_package id=’122′]