Get week of month with Joda-Time

前端 未结 4 435
半阙折子戏
半阙折子戏 2021-01-12 20:00

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

4条回答
  •  攒了一身酷
    2021-01-12 20:41

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

提交回复
热议问题