Possible Duplicate:
How to calculate the date difference between 2 dates using php
Hi,, i am using dd-mm-yyyy format for date; can u pls give me the code how to find the difference between two dates?
Possible Duplicate:
How to calculate the date difference between 2 dates using php
Hi,, i am using dd-mm-yyyy format for date; can u pls give me the code how to find the difference between two dates?
If you're using a string in the format DD-MM-YYYY for your date values, you have two things you need to do: 1. Convert the string into a date, and 2. Get the difference between the dates. I'll take those in reverse order:
In JavaScript, performing arithmetic on Date
instances will use their underlying "time" value (date.getTime()
), which is the number of milliseconds since The Epoch (and can be negative). So to get the difference, just subtract one date from another:
var d1 = new Date(2010, 0, 1); // January 1st 2010
var d2 = new Date(2010, 1, 1); // February 1st 2010
var diff = d2 - d1; // Milliseconds between the dates (in this case, 2678400000)
If you have your dates in a string in the form DD-MM-YYYY, you'll have to dice up that string to create the Date
instances. String#split
will split up the string using the delimiter you give it (-
in this case) and create an array of strings, and then parseInt
will convert those strings into numbers (we specify the radix, in this case 10
for decimal, so that we don't have to worry about parseInt
seeing a leading 0
and assuming octal):
function ddmmyyyyToDate(str) {
var parts = str.split("-"); // Gives us ["dd", "mm", "yyyy"]
return new Date(parseInt(parts[2], 10), // Year
parseInt(parts[1], 10) - 1, // Month (starts with 0)
parseInt(parts[0], 10)); // Day of month
}
var s1 = "01-01-2010"; // January 1st 2010
var d1 = ddmmyyyyToDate(s1);
var s2 = "01-02-2010"; // February 1st 2010
var d2 = ddmmyyyyToDate(s2);
var diff = d2 - d1;
The reason you have to do it yourself is that it's only recently that there was a standard string format you could pass into new Date()
to have it parse it into a date instance. A standard (a simplified version of ISO8601) was introduced in the 5th edition spec, but isn't well-supported in the wild yet.
// php
echo strtotime($date1) - strtotime($date2); // echos the time difference between $date1 and $date2 in seconds
In JavaScript, take a look at the Datejs library, which makes working with dates in JavaScript easy. You will need to download the full package which contains globalization modules which affect how dates are parsed and rendered. With the appropriate CultureInfo file:
Date.parse('11-12-2010') - Date.parse('25-12-2010');
This statement returns -1209600000
ms; divide to get other units – /1000/60/60/24 = -14
days. (Dividing by 1000
ms, 60
seconds, 60
minutes, 24
hours to get days.