Reputation: 362
I have two dates as From and To in String format as 1/11/2015
and 15/11/2015
. What are the ways to find the difference in days between two dates. Remember the dates are in String format not in JavaScript Date format.
Upvotes: 1
Views: 1447
Reputation: 2766
You can use moment js to achieve your desired result.
var fromDt = new Date("11/1/2015"), toDt = new Date("11/15/2015");
var moment = require('moment');
Convert into millisecond.
var fromDate = moment(fromDt).format('X') * 60000;
var toDate = moment(toDt).format('X') * 60000;
Get the difference.
var diffMs = toDate - fromDate;
Now you can use the desired format you want.
NOTE :- diffMs will give you difference in milliseconds. You can convert it to know the difference.
Hope this will help.
Upvotes: 0
Reputation: 1178
Below is the function for mmddyy format of date
function dateDiff(d1,d2){
var date1 = new Date(d1)
var date2 = new Date(d2);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
return(diffDays);
}
The Date function is capable of handling strings. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Upvotes: 0
Reputation: 6397
It's actually pretty simple in JS.
i.e. in JS
//Since your dates are in DD/MM/YY we have to modify it a bit
var d1 = '1/11/2015'.split('/')
var d2 = '15/11/2015'.split('/')
//This is our converted format that is MM/DD/YY
var normd1 = [d1[1],d1[0],d1[2]].join('/')
var normd2 = [d2[1],d2[0],d2[2]].join('/')
//Get the difference in ms and use the absolute value incase you switched the days
var diff = Math.abs(Date.parse(norm1) - Date.parse(normd2))
//convert the difference to days
var days = diff/(1000*60*60*24 )
Date.parse
converts a date string into a millisecond UNIX timestamp, i.e. number of milliseconds since Jan 1, 1970.
Upvotes: 0
Reputation: 68393
You can convert them to dates using
function convertToDate(str)
{
var dateArr = str.split("/");
return new Date(dateArr[2], dateArr[1], dateArr[0])
}
var date1 = convertToDate("1/11/2015");
var date2 = convertToDate("15/11/2015");
var diffInDays = (date1.getTime() - date2.getTime())/ (1000*60*60*24);
alert( Math.ceil( Math.abs( diffInDays ) ) );
getTime
returns number of milliseconds since 1970, so you need to convert them to days by dividing it with 24 * 60 *60 * 1000
()
Upvotes: 4