1

Seems that solution from How to calculate the number of days between two dates using JavaScript? work fine exept for case : 30.4.2016 - 1.5.2016 it calculate 2 days ( in real 1 ) 29.2.2016 - 1.3.2016 it calculate 3 days ( in real 1 )

May be someone already found solution for these cases ?

This function from link
function count_days(){ // Expecting resuls: positive when date1 > date2  ; negative  when date1 < date2  
            var $obj = "dd.mm.YYYY";
            var $obj2 = "dd.mm.YYYY";
            if($obj2.value){
                $start=$obj.value.split(".");
                var date1 = new Date($start[2],$start[1],$start[0]); // Converted date to ("YYYY,mm,dd")
                var $stop=$obj2.value.split(".");
                var date2 = new Date($stop[2],$stop[1],$stop[0]); // Converted date to ("YYYY,mm,dd")
                var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
                var diffDays = (date2.getTime() - date1.getTime())/(oneDay);
                if(diffDays >= 0){
                    return Math.abs(diffDays)+1;
                } else {
                    return diffDays-1;
                }
            }
return false; // No date2 nothing to compare  
}
// Expecting resuls in full days (24h):  
//(5.5.2016 - 5.5.2016) =  1 day (days equal)  
//(29.2.2016 - 1.3.2016) =  1 day  
//(30.4.2016 - 1.5.2016) =  1 day  
//(4.5.2016 - 5.5.2016) =  2 days  
//(29.2.2016 - null) = False   
//(1.3.2016 - 29.2.2016) = -1 day  
//(1.5.2016 - 30.4.2016) = -1 day  
//(5.5.2016 - 4.5.2016)  = -2 day  
Community
  • 1
  • 1
Vitaly
  • 15
  • 3
  • and what stops you from finding a solution? – Sandeep Nayak May 06 '16 at 05:46
  • 2
    `Date(2016, 4, 30)` is not 30.4.2016. `Date(2016, 3, 30)` is. You are calculating the difference between wrong dates and getting the correct result for wrong input. There's 3 days between 29.3 and 1.4, and there's 2 days between 30.5 and 1.6. – Amadan May 06 '16 at 05:49
  • related http://stackoverflow.com/questions/36030754/how-to-calculate-number-of-day-name-between-2-dates-in-javascript – gurvinder372 May 06 '16 at 05:51

3 Answers3

1

Note that new Date()'s month value starts from 0 (0 - January, 1 - February and etc...).

var 
  a = new Date(2016, 01, 29), // Feb 29 2016 00:00:00
  b = new Date(2016, 02, 1); // Mar 01 2016 00:00:00

alert((+b - +a) / 1000 / 60 / 60 / 24); // 1 day

An expression (+b - +a) - returns you the difference between two dates in milliseconds (1 second = 1000 millisecond).

As result you can convert:

  • milliseconds to seconds: (+b - +a) / 1000 = 86400 seconds

  • seconds to minutes: (+b - +a) / 1000 / 60 = 1440 minutes

  • minutes to hours: (+b - +a) / 1000 / 60 / 60 = 24 hours

  • hours to days: (+b - +a) / 1000 / 60 / 60 / 24 = 1 day

+a and +b - give you integer value representing the number of milliseconds since 1 January 1970 00:00:00 for each dates.

Read more about new Date()

The JavaScript date is based on a time value that is milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
  • -100,000,000 days to 100,000,000 only on x64 FreeBSD on x32 FreeBSD its begins with zero (almost saw this on FreeBSD 8.0 or 9.0 ) – Vitaly May 06 '16 at 07:16
  • And Your solution solution3= (+date2 - +date1) / 1000 / 60 / 60 / 24; Give me these Results : (29.2.2016 - 1.3.2016) solutionResult: 3 (must be 1) (30.4.2016 - 1.5.2016) solutionResult: 2 (must be 1) (4.5.2016 - 5.5.2016) solutionResult: 1 (must be 2) (5.5.2016 - 5.5.2016) solution3: 0 – Vitaly May 06 '16 at 07:34
  • Sorry but Your code give me the same results as I already have , it does not count corectly (as I expected) – Vitaly May 06 '16 at 08:02
  • Lets check: 29.2.2016 -> 29 February 2016 -> `var a = new Date(2016, 01, 29);` 1.3.2016 -> 1 march 2016 -> `var b = new Date(2016, 02, 1);` **Result: (+b - +a) / 1000 / 60 / 60 -> 1 DAY**. What is incorrect?? – Ali Mamedov May 06 '16 at 08:42
  • Виталий, посмотрите внимательно на пример. Используя Ваши даты я получаю значение 1, а не 3. Откуда Вы берете эти нерпавильные данные?? – Ali Mamedov May 06 '16 at 08:43
  • 1
    Finaly I found problem, thx @Ali-Mamedov ! My mistake was in new Date() convertion lines var date1 = new Date($start[2],$start[1],$start[0]); -wrong var date2 = new Date($stop[2],$stop[1],$stop[0]); -wrong var date1 = new Date($start[2],$start[1]-1,$start[0]);- Right var date2 = new Date($stop[2],$stop[1]-1,$stop[0]);- Right P.s. Stupid question . How get new line in messages (tryed dubble space on end and )?? – Vitaly May 06 '16 at 10:56
  • 1
    Спасибо Али, что указали на ошибку. Я забыл отнять у месяца 1 когда присваивал new Date(). – Vitaly May 06 '16 at 11:10
  • И Вам спасибо. я поэтому выделил текст **Note that new Date()'s month value starts from 0 (0 - January, 1 - February and etc...).** :). Этот момент с отниманием единицы в месяце очень коварный. очень! Надо просто запомнить и не забывать. Рад что мой ответ оказался полезным для Вас – Ali Mamedov May 06 '16 at 11:16
0

This code works for every case:

      function fmtDate( when ) {
    function D2( val ) {
      return ( val < 10 ) ? '0' + val : '' + val;
    }
    return D2( when.getMonth() + 1 ) + '/' + D2( when.getDate() ) + '/' + when.getFullYear();
  }

  function workdays( d1, d2 ) {
    var result = 0;
    var d0 = new Date();
    var negative = 1;
    if ( ( typeof( d1 ) == typeof( d2 ) ) && ( typeof( d1 ) == typeof( d0 ) ) ) {
      if ( d2 < d1 ) {  // Exchange/swap the dates
        d0 = d2;
        d2 = d1;
        d1 = d0;
        negative = -1;
      }
      for ( d = d1; d < d2; d.setDate( d.getDate() + 1 ) ) {
       dow = d.getDay();     // Day Of Week: 0 (Sun) .. 6 (Sat)
       when = fmtDate( d );  // Formatted date
        if ( ( dow >= 0 ) && ( dow <= 6 )) {

            result++;
        }
      }
    } else {
      alert( 'workdays() - parameter error - date objects required.' );
    }
    return result
  }

and if you remove "=" from this line:

if ( ( dow >= 0 ) && ( dow <= 6 ))

You can use this for working out how many workdays (excluding Sat and Sun)

Siobhan Holubicka
  • 147
  • 1
  • 4
  • 17
0

Finaly good working code

function count_days(){ 
            var $obj = "dd.mm.YYYY";
            var $obj2 = "dd.mm.YYYY";
            if($obj2.value){
                $start=$obj.value.split(".");
                var date1 = new Date($start[2],$start[1]-1,$start[0]); // Converted date to ("YYYY,mm,dd")
                var $stop=$obj2.value.split(".");
                var date2 = new Date($stop[2],$stop[1]-1,$stop[0]); // Converted date to ("YYYY,mm,dd")
                var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
                var diffDays = (date2.getTime() - date1.getTime())/(oneDay);
                if(diffDays >= 0){
                    return Math.abs(diffDays)+1; // positive as date1 > date2    
                } else {
                    return diffDays-1;  //negative  as date1 < date2
                }
            }
return false; // No date2 nothing to compare  
}
Vitaly
  • 15
  • 3