count Saturday and Sunday in a range of dates with datapicker

1

How can I know when Saturdays and Sundays are in a range of dates? 01-01-2017 & 01-20-2017 (for example), knowing that datapicker (bootstrap) has a

taking arrangement = > Sunday [0] [Monday [1] Tuesday [2] Wednesday [3] Thursday [4] Friday [5] Saturday [6]

    
asked by matteo 24.02.2017 в 16:58
source

3 answers

2

Here is a solution:

function cuentaFindes(){
    var inicio = new Date("2017-02-24"); //Fecha inicial
    var fin = new Date("2017-03-10"); //Fecha final
    var timeDiff = Math.abs(fin.getTime() - inicio.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); //Días entre las dos fechas
    var cuentaFinde = 0; //Número de Sábados y Domingos
    var array = new Array(diffDays);

    for (var i=0; i < diffDays; i++) 
    {
        //0 => Domingo - 6 => Sábado
        if (inicio.getDay() == 0 || inicio.getDay() == 6) {
            cuentaFinde++;
        }
        inicio.setDate(inicio.getDate() + 1);
    }

   return cuentaFinde;
}
    
answered by 24.02.2017 / 17:54
source
1

This I think would be what you are looking for:

Remember that the week counts from 0; Sunday = 0 and Saturday = 6

function contadorSabadosYDomingos(fechaInicial,fechaFinal){
fechaInicial = fechaInicial.split("-");
fechaFinal = fechaFinal.split("-");

var dtInicial = new Date(fechaInicial[2], fechaInicial[1] - 1, fechaInicial[0]);
var dtFinal =new Date(fechaFinal[2], fechaFinal[1] - 1, fechaFinal[0]);

var contadorDias = 0;
while(dtInicial <=dtFinal){
    if(dtInicial.getDay()===0||dtInicial.getDay()===6){
     console.log("dia contado:"+dtInicial);
     contadorDias++;
    }
dtInicial = new Date(dtInicial.getTime()+86400000);// se agrega un dia

}
return contadorDias;
}
    
answered by 24.02.2017 в 17:52
0

Another solution would be to assign a variable to the starting date, do a repeat cycle where you will add a day to that variable and you will be asking if the date is Saturday, if so you add a + 1 to the counter, the cycle ends when the date you are adding one day reaches the end date. You would have something like that in C #, you would have to spend it no more

public int DiasSabados(DateTime inicio, DateTime fin)
    {
        int contadorSabados = 0;
        while (inicio < fin)
        { 
            if ( inicio.DayOfWeek == DayOfWeek.Saturday)
            {
                contadorSabados++;
            } 
        inicio = inicio.AddDays(1);
        }
         return contadorSabados;
    }

JavaScript

while(inicio < fin) 
{
    if (inicio.getDay() == saturday)
    {
        contadorSabados++;
    }
    inicio.setDate(inicio.getDate() + 1);
}
    
answered by 24.02.2017 в 17:17