Get the week of the month with Joda-Time

Is it possible to parse the date and extract the week of the month using Joda-Time . I know that this can be done during the week of the year, but I cannot find how / if I can extract the week of the 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 tried the template "yyyyMMW", but it is not accepted.

+6
source share
2 answers

The current version of joda-time does not support the week of the month, so you should use some workaround.
1) For example, you can use the following 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); } 

Using:

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

2) You can use Java 8 because the Java API supports a weekly field.

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

This option in Joda is probably nicer:

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

Source: https://habr.com/ru/post/970992/


All Articles