Search code examples
datetimejodatime

Get week of month with Joda-Time


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 extract the week of month.

Example: 2014-06_03 where 03 is the third week of this month

DateTime dt = new DateTime();
String yearMonthWeekOfMonth = dt.toString("<PATTERN for the week of month>");

I have tried the pattern "yyyyMMW" but it is not accepted.


Solution

  • 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));