-1

very quick question.

I have a datetime stored in my sql database. I am using this date to calculate the difference in time between those datetimes like the following:

var date1 = new Date(request[0].RequestDate.toString()); //coming from my db
var date2 = new Date(); // current datetime
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // calc diff
var rod= timeDiff / (1000 * 3600 * 24);
rod= rod.toFixed(2); // result that I want

However, this will give me the difference between those 2 dates including Sat and Sun.. How can I change my JS code to exclude Sat and Sun.

PS note: the day in the database that I am dealing with has, for example, the following format: Mon Dec 12 2016 10:23:50 GMT-0500 (Eastern Standard Time) and I need the diff in "time" as you can notice in my JS code.

Thanks!

Ray
  • 781
  • 2
  • 17
  • 42

1 Answers1

-1

A simple for loop going through the total days, creating a date object for that day and incrementing a new days total count should do it:

var days = 0;
for (d = 0; d <= rod; d++) {
    var thisDate = new Date(
        date1.getYear(),
        date1.getMonth(),
        (date1.getDate()+d),
        date1.getHours(),
        date1.getMinutes(),
        date1.getSeconds()
    );

    // 0: Sunday, 6: Saturday
    if (thisDate.getDay() > 0 &&
        thisDate.getDay() < 6) {
        days++;
    }
}
days.toFixed(2);

To now get the date differences from that in time, you only need to construct a new date from the start date using the new total number of days you have from the above:

var startDate = new Date(date1.toDateString());
date1.setDate(date1.getDate() + days);
var endDate = new Date(date1.toDateString());
John Joseph
  • 921
  • 5
  • 14
  • This is a poor, slow solution to a question that already has great answers on the duplicate question. – 4castle Dec 12 '16 at 16:34
  • The only difference I can see between the answers on the other page and this one is they use setDate on the existing date object rather than construct a new one. Also, those other answers are longer. This is the simplest form, although using setDate would make it smaller still. – John Joseph Dec 12 '16 at 16:37
  • If you think the other answers are the same, please flag as a duplicate. – 4castle Dec 12 '16 at 16:43
  • I hadn't read the comments on the question before posting the answer, and the OP has also made an edit to say he wants the difference in timestamps rather than actual days. – John Joseph Dec 12 '16 at 16:45