Based on a date, know what is the week of the year

Asked

Viewed 1,983 times

2

Considering that 1 year has 12 months and that each month has 30 days (same February), and that 1 January belongs to week 1 and 30 December to week 52, create a method that when receiving a date (in this case one day and one month because the year makes no difference ) indicate which is the week. In case anyone can help me, thank you.

2 answers

1

Can solve using the class Gregoriancalendar, which allows the manipulation of dates for both the Gregorian calendar (the one 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.

  • But I think it makes a difference, right? The proposal is that every month of the year is 30 days.

1


It would be something + or - like... But it’s just the same logic, because I didn’t write in an IDE... n I 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 you the right answer because normally the year starts with the first week in December of last year...

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

Take a look here: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=java%20get%20week%20number

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

  • It makes perfect sense, and it’s very simple. Thank you.

Browser other questions tagged

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