Is it possible to calculate the weeks of one month in jodatime?
I need something like this:
Month: July
Month: August
I know that i can get the week of Year in joda time like this:
new LocalDate().weekOfWeekYear()
But i don´t know how to get the related dates.
To retrieve the range of a week, just create an object pointing to the first and last day of the week, then just pull the day of month from it.
int weekOfYear = 32;
LocalDate firstDay = new LocalDate().withWeekOfWeekyear(weekOfYear).withDayOfWeek(1);
LocalDate lastDay = new LocalDate().withWeekOfWeekyear(weekOfYear).withDayOfWeek(7);
System.out.println("Week of Year "+weekOfYear+"; "+firstDay.toString("d MMM")+" - "+lastDay.toString("d MMM"));
You can also extract the day like this:
int weekStart = firstDay.getDayOfMonth();
int weekEnd = lastDay.getDayOfMonth();
You can then use the same technique to retrieve the weeks in a month as well.
int firstWeekInMonth = new LocalDate().withMonthOfYear(month).withDayOfMonth(1).getWeekOfYear();
int lastWeekInMonth = new LocalDate().withMonthOfYear(month).dayOfMonth().withMaximalValue().getWeekOfYear();
Probably you might want to limit the start and end-dates to stay within the range of the month, otherwise you could get things like '30 - 5 Sep'.
fixing some variables:
int weekOfYear = 32;
LocalDate firstDay = new LocalDate().withWeekOfWeekyear(weekOfYear).withDayOfWeek(1);
LocalDate lastDay = new LocalDate().withWeekOfWeekyear(weekOfYear).withDayOfWeek(6);
int weekStart = firstDay.getDayOfMonth();
int weekEnd = lastDay.getDayOfMonth();
System.out.println("Week of Year "+weekOfYear+"; "+weekStart+"-"+weekEnd+" "+month);
My solution, considering the other answers
public List<Pair<LocalDate, LocalDate>> getWeeksInMonth(LocalDate data) {
int firstWeekInMonth = data.withDayOfMonth(1).getWeekOfWeekyear();
int lastWeekInMonth = data.dayOfMonth().withMaximumValue().getWeekOfWeekyear();
List<Pair<LocalDate, LocalDate>> weeks = new cicero.minhasfinancas.util.array.ArrayList<>();
while (firstWeekInMonth <= lastWeekInMonth) {
LocalDate firstDay = new LocalDate().withWeekOfWeekyear(firstWeekInMonth).withDayOfWeek(1);
LocalDate lastDay = new LocalDate().withWeekOfWeekyear(firstWeekInMonth).withDayOfWeek(7);
weeks.add(new Pair<>(firstDay, lastDay));
firstWeekInMonth++;
}
return weeks;
}
public class Pair<V1, V2>{
V1 first;
V2 second;
public Pair(V1 first, V2 second) {
this.first = first;
this.second = second;
}
public V1 getFirst() {
return first;
}
public void setFirst(V1 first) {
this.first = first;
}
public V2 getSecond() {
return second;
}
public void setSecond(V2 second) {
this.second = second;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With