I want to get number of weeks in a particular month

后端 未结 5 1079
深忆病人
深忆病人 2021-01-01 16:01

i want to get number of weeks in current month.That including the previous month\'s days in the last week and the first week days in the next month.

Something like t

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 16:30

    use WEEK_OF_MONTH will be better, no cross year issue.

    public static void main(String[] args) throws Exception {
      for (String m : new String[] { "2012-11", "2012-12", "2013-01", "2013-02", "2013-03",
                  "2013-04", "2013-05", "2013-06" }) {
          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
          Date date = format.parse(m);
          Calendar c = Calendar.getInstance();
          c.setTime(date);
    
          int start = c.get(Calendar.WEEK_OF_MONTH);
    
          c.add(Calendar.MONTH, 1);
          c.add(Calendar.DATE, -1);
          int end = c.get(Calendar.WEEK_OF_MONTH);
          System.out.println(" # of weeks in " + format.format(c.getTime())
                  + ": " + (end - start + 1));
      }
    }
    

    results:

    # of weeks in 2012-11: 5
    # of weeks in 2012-12: 6
    # of weeks in 2013-01: 5
    # of weeks in 2013-02: 5
    # of weeks in 2013-03: 6
    # of weeks in 2013-04: 5
    # of weeks in 2013-05: 5
    # of weeks in 2013-06: 6
    

提交回复
热议问题