user3060271
user3060271

Reputation: 1

Get days between two Dates

Function countdays(){


var oneday = 24*60*60*1000;

var sd = $('#sdate').val();// Start date from DOM element type input text(DD/MM/YYYY)

var start_date = new Date(sd);

var ed = $('#edate').val();// End date from DOM element type input text(DD/MM/YYYY)

var end_date = new Date(ed);


var days = Math.floor((start_date.getTime() - end_date.getTime())/(oneday));

alert(days);

}

I am trying to run this function, when i put date in format DD/MM/YYYY for start date and end date, JavaScript is taking as MM/DD/YYYY.

Is there any way by which I can keep my date format as DD/MM/YYYY and get difference between start date and end date

Upvotes: 0

Views: 757

Answers (3)

Vikram Deshmukh
Vikram Deshmukh

Reputation: 15706

Try handling the date format yourself.

function parseDate(str) {
    var d = str.split('/')
    return new Date(parseInt(d[2]),parseInt(d[1]) - 1, parseInt(d[0]));
}
function countdays(){

var oneday = 24*60*60*1000;

var start_date = parseDate($('#sdate').val());
var end_date = parseDate($('#edate').val());


var days = Math.floor((start_date.getTime() - end_date.getTime())/(oneday));

alert(days);
}

Upvotes: 0

Ivan Plenty
Ivan Plenty

Reputation: 76

May I make a pitch for MomentJS when manipulating DateTimes in JavaScript? Raw Date objects have a lot of corner cases. If you use MomentJS, you can make use of the difference method.

var start_date = moment(sd);
var end_date = moment(ed);

var days = end_date.diff(start_date, "days");

console.log(days); // should be the integer you want to test

What's extra nice about using MomentJS is that the code is readable when you come back to the logic 3 months from now, and it allows you to adjust for weird things like time zones.

Upvotes: 1

sdespont
sdespont

Reputation: 14025

Never use new Date(string) because it depends on the user's locale.

You should break the date string into year, month and day and then call new Date(year, month - 1, day)

Your are right to use getTime to find the number of days.

Upvotes: 1

Related Questions