Validation and counting of days of a date

Asked

Viewed 898 times

-3

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

If the date is correct, construct another function that will count the days from the beginning of the year to the informed date. Again passing the date as parameter. For example, how many days is 12/09/2015? Answer 258.

The rest I did, I’m just not getting this day count.

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";
        }

    }
  • Is there a problem, or what is the purpose of the question? If possible, make it clearer what you want to do and improve the formatting of the question

  • The question is old, but a detail that was not put in the answers: to know how many days have passed since the beginning of the year, you can use new DateTime(ano, mes, dia).DayOfYear - the difference is that DayOfYear also counts the day 1 of January. It is already calculated the difference, as they did in the answers, does not count (but then it would be enough to subtract 1)

3 answers

3

Go some tips:

The date check can thus be simplified:

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 make a TryParse(). Has example for date. Something like that:

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;
}

Being with the valid date just subtract from it the first day of January of that year and will have the days without major worries. Something like this:

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

I put in the Github for future reference.

Then I take a test.

1


Just as Maniero said by subtracting the date in question with the date beginning on the 1st of the same year, he gets an object of the type TimeSpan which represents the time difference between two dates. This time difference can be seen in several units being one of them in days.

Example of use in its 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 iData of the parameters because it is not necessary for the calculation that is being done, as I also changed the type of return of the method to int to return only the amount of days that has passed.

To use in order to display on a label as you were doing, 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 TimeSpan corresponding, thus:

TimeSpan diferenca = (data - datadia1);
return diferenca.Days;
  • Thanks for the Isac tip.

  • I’m trying to use your method is what looks more like what I use, but it’s still returning error, could you give me a hand. " Additional information: Year, Month and Day parameters describe a non-representable Datetime."

  • @Thiagosaracine Confirm that you call the parameters in the correct order, this being iDia, iMes, iAno, as it is in ContarDias(iDia, iMes, iAno);. Reversing the order of the values when trying to create the date will create a date with incorrect values, and generate the error you specified

0

To count the days, you can use the .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 on dotNetFiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.