Is it possible to parse a date and extract the week of month using Joda-Time. I know it is possible to do it for the week of year but I cannot find how/if it is possible to
For the case you don't like calculations so much:
DateTime date = new DateTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date.toDate());
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
Current joda-time
version doesn't support week of month, so you should use some workaround.
1) For example, you can use next method:
static DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM_'%d'");
static String printDate(DateTime date)
{
final String baseFormat = FORMATTER.print(date); // 2014-06_%d
final int weekOfMonth = date.getDayOfMonth() % 7;
return String.format(baseFormat, weekOfMonth);
}
Usage:
DateTime dt = new DateTime();
String dateAsString = printDate(dt);
2) You can use Java 8, because Java's API supports week of month field.
java.time.LocalDateTime date = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM_W");
System.out.println(formatter.format(date));
If the start day of week is Monday then you can use it:
public int getWeekOfMonth(DateTime date){
DateTime.Property dayOfWeeks = date.dayOfWeek();
return (int) (Math.ceil((date.dayOfMonth().get() - dayOfWeeks.get()) / 7.0)) + 1;
}
This option in Joda is probably nicer:
Weeks.weeksBetween(date, date.withDayOfMonth(1)).getWeeks() + 1