Search week number of the year through a date in C#

Asked

Viewed 998 times

2

I’m writing a function that gets a string with a date (format dd/mm/aaaa) and it must return a date (in the same format) 4 weeks later.

Example:

Entrada: 07/04/2016
saída: 05/05/2016

I read about it and thought of the following logic:

Read the date and turn the corresponding week into integer, add 4 and do the opposite process.

Follows code:

    //entrada 07/04/2016
    private string CalcularDataEntrega(string dataEntrada)
    {
        //regra: Data Geração + 4 Semanas;
        DateTime dataGen = DateTime.Parse(dataEntrada);
        Calendar cal = new GregorianCalendar();
        int semanaInicio = cal.GetWeekOfYear(dataGen); //erro
        int semanaFim = semanaInicio + 4;

        //retornar data com base na semana
        string dataSaida; //o que colocar?

        return dataSaida;
    }

In this Example from the Microsoft documentation it was not clear what exactly this function GetWeekOfYear returns (integer, string?).

  • 1

    I don’t know if I understand what you want, but is there any reason to avoid adding 28 days?

  • 1

    dataGen.Adddays(28);

  • . . . really, hadn’t thought of it, it seems incredibly obvious. Thanks anyway

2 answers

2


Just do this:

DateTime.Parse(dataEntrada).AddDays(28).ToString()

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I am assuming that the date will be guaranteed to be in an appropriate format. If this is not guaranteed, there will be an exception. Ideally it would be good to treat this somehow, maybe using a TryParse(). Avoid working with stored dates like string whenever possible.

  • It gave to understand yes friend, I only need to see with the client if they are 28 days run even or I disregard non-working days. yet the implementation will serve. Thank you

  • 1

    If it’s a working day, it would have to be a little more sophisticated and here comes the twist of treating holidays, already out of a trivial solution to something relatively complex and that most programmers do not even realize.

1

The function you are looking for is this same Getweekofyear and it will return you an integer (Int32), as described on the page.

Return Value Type: System.Int32 A Positive integer that represents the week of the year that includes the date in the time Parameter.

Hugs,

  • True dude, I hadn’t seen on the link. Thank you

Browser other questions tagged

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