Get week of month with Joda-Time

前端 未结 4 429
半阙折子戏
半阙折子戏 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:25

    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);
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2021-01-12 20:43

    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;
    }
    
    0 讨论(0)
  • 2021-01-12 20:46

    This option in Joda is probably nicer:

    Weeks.weeksBetween(date, date.withDayOfMonth(1)).getWeeks() + 1
    
    0 讨论(0)
提交回复
热议问题