Joda-Time获得一周的一周

时间:2014-06-18 08:14:48

标签: datetime jodatime

是否可以使用Joda-Time解析日期并提取月份周。我知道有可能在一年中这么做,但我找不到如何/如果有可能提取一周的一周。

示例:2014-06_03其中03是本月的第三周

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

我尝试过“yyyyMMW”模式,但不接受。

4 个答案:

答案 0 :(得分:5)

Joda中的这个选项可能更好:

Weeks.weeksBetween(date, date.withDayOfMonth(1)).getWeeks() + 1

答案 1 :(得分:4)

当前joda-time版本不支持一周中的某周,因此您应该使用一些解决方法 1)例如,您可以使用下一个方法:

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

用法:

DateTime dt = new DateTime();
String dateAsString = printDate(dt);  

2)您可以使用Java 8,因为Java的API支持星期几字段。

  java.time.LocalDateTime date = LocalDateTime.now();
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM_W");
  System.out.println(formatter.format(date));

答案 2 :(得分:0)

对于这种情况,您不太喜欢计算:

    DateTime date = new DateTime();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date.toDate());
    int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);

答案 3 :(得分:0)

如果一周的开始日期是星期一,那么您可以使用它:

public int getWeekOfMonth(DateTime date){
    DateTime.Property dayOfWeeks = date.dayOfWeek();
    return (int) (Math.ceil((date.dayOfMonth().get() - dayOfWeeks.get()) / 7.0)) + 1;
}