Validating and counting days of a date [closed]

-3

Consider an informed date on a form. Build a function that checks whether the date is correct (considering leap year, April 31, etc). You need to pass the date entered on the form as a parameter.

If the date is correct, build another function that will count the days from the beginning of the year to the date entered. Again passing the date as parameter. For example, how many days is 9/29/2015? Answer 258.

The rest I did, I just can not do this count of days.

This is all being done in C # with Windows Forms:

    private void btnVerificar_Click(object sender, EventArgs e)
    {

        int iDia = Convert.ToInt32(txtDia.Text);
        int iMes = Convert.ToInt32(txtMes.Text);
        int iAno = Convert.ToInt32(txtAno.Text);
        VerificaAno(iAno);

        int iData = Convert.ToInt32(DateTime.Now.Year);
        VerificaData(iDia, iMes, iAno);


        int iTotalDias = Convert.ToInt32(DateTime.Now.Year);
        ContarDias(iDia, iMes, iAno, iData);

    }

    private void VerificaData(int iDia, int iMes, int iAno)
    {
        int iData = DateTime.DaysInMonth(iAno, iMes);

        if (iDia > iData || iDia < 1)
        {
            lblData.Text = "DATA INVÁLIDA";
            lblData.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblData.Text = "DATA VÁLIDA";
            lblData.ForeColor = System.Drawing.Color.Blue;
        }

    }

    private void ContarDias(int iDia, int iMes, int iAno, int iData)
    {
       #####NO CASO SERIA AQUI QUE EU IRIA FAZER O MEU CÓDIGO#####
    }


    private void VerificaAno(int iAno)
    {

        if (((iAno % 400) == 0) || (iAno % 4 == 0 && iAno % 100 != 0))
        {
            lblAnoBissexto.Text = "ANO BISSEXTO";
        }
        else
        {
            lblAnoBissexto.Text = "ANO NÃO BISSEXTO";
        }

    }
    
asked by anonymous 06.09.2017 / 04:54

3 answers

1

Just as bigown said by subtracting the date in question with the date starting on the 1st of the same year you get an object of type TimeSpan " that represents the time difference between two dates. This time difference can be seen in several units being one in days.

Example usage in context:

private int ContarDias(int iDia, int iMes, int iAno)
{
    DateTime data = new DateTime(iAno, iMes, iDia); //data com ano mes e dia
    DateTime datadia1 = new DateTime(iAno, 1, 1); //data com ano, mes 1 e dia 1

    return (data - datadia1).Days; //devolver a diferença em dias
}

Notice that I removed the% w / o of the parameters because it is not necessary for the calculation that is being done, as I also changed the return type of the method to iData so that it returns only the number of days that passed .

To use it to show a Label as it was, you need to call the function like this:

AlgumaLabel.Text = "Dias: " + ContarDias(iDia, iMes, iAno);

If we wanted to be explicit in the difference of dates could be stored the same in the object int corresponding, like this:

TimeSpan diferenca = (data - datadia1);
return diferenca.Days;
    
06.09.2017 / 12:14
3

Go some tips:

Date verification can be simplified as follows:

try {
    var dataAtual = new DateTime(Convert.ToInt32(txtDia.Text), Convert.ToInt32(txtMes.Text), Convert.ToInt32(txtAno.Text));
    lblData.Text = "DATA VÁLIDA";
    lblData.ForeColor = System.Drawing.Color.Blue;
} catch (ArgumentOutOfRangeException ex) {
    lblData.Text = "DATA INVÁLIDA";
    lblData.ForeColor = System.Drawing.Color.Red;
}

But I'm not a fan, I prefer something that creates a string and do a % with% . You have example for date . Something like this:

if (DateTime.TryParseExact($"{Convert.ToInt32(txtDia.Text)}/{ Convert.ToInt32(txtMes.Text)}/{Convert.ToInt32(txtAno.Text)}", "dd/MM/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out var dataAtual);
    lblData.Text = "DATA VÁLIDA";
    lblData.ForeColor = System.Drawing.Color.Blue;
} else {
    lblData.Text = "DATA INVÁLIDA";
    lblData.ForeColor = System.Drawing.Color.Red;
}

With the valid date, it is enough to subtract from it the first of January of that year and have the days without major concerns. Something like this:

static int ContarDias(DateTime dataAtual) => (dataAtual - new DateTime(dataAtual.Year, 1, 1)).Days;

Then I'll do a test.

    
06.09.2017 / 05:01
0

To count days, you can use .TotalDays , see:

static int dias(DateTime data) //Pede uma data como parâmetro
{
    DateTime data2 = new DateTime(data.Year, 1, 1); //Cria uma data nova, com base no ano da variavel data
    return (int)(data - data2).TotalDays; //Retorna os dias. É preciso fazer o cast porque vem em double
}

See working at dotNetFiddle .

    
06.09.2017 / 12:11