Based on a date, know what week of the year

2

Considering that 1 year is 12 months and that each month has 30 days (even February), and that January 1 belongs to week 1 and December 30 to week 52, create a method that upon receiving a date (in the case a day and a month because the year does not make a difference) indicate the week. If anyone can help me, thank you.

    
asked by anonymous 06.06.2015 / 18:44

2 answers

1

It would be something + or - like this ... But it's just the logic itself, because I did not write in an IDE ... n you can say that the code is right ^^

//Aqui temos uma função que retornará uma variável do tipo inteiro
public int converterData(int _dia, int _mes){  

    //Aqui uma variável que vai armazenar o número de dias até aquela data
    int quantidadeDias = (((_mes - 1) * 30) + _dia);

    //Aqui dividimos por 7, ou seja, 7 dias na semana para saber o número de semanas
    int numeroSemana = (quantidadeDias / 7);

    //Aqui só retornamos a resposta
    return numeroSemana;
}

To call the function you will do something like this:

//Pronto, você já tem a resposta de qual semana vai ser no dia 05 de dezembro
int resposta = converterData(5,12);

The logic is basically this, but it will never return the right answer because normally the year begins with the first week in December of last year ...

This is certainly not the best way ... I think java should have some lib for calendars

Take a look here: link

Many people have had the same doubt, you can find something;)

    
06.06.2015 / 19:19
1

You can resolve using the GregorianCalendar class , which allows manipulation of dates for both the Gregorian calendar (what we currently use) and Julian:

Date data = new Date(2015, 06 /* Mês */, 01/* Dia */);
Calendar cal = new GregorianCalendar();
cal.setTime(data);
int semana = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println(semana);

See working here .

    
06.06.2015 / 19:18