问题描述
可以使用解析日期并提取月份。我知道这是可能的一年的一周,但我找不到/如果可以提取一个月的一周。
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 extract the week of month.
示例:2014-06_03其中03是本月的第三周
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>");
我已经尝试了模式yyyyMMW,但不被接受。
I have tried the pattern "yyyyMMW" but it is not accepted.
推荐答案
当前 joda-time
版本不支持星期几,所以你应该使用一些解决方法。
1)例如,您可以使用下一个方法:
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);
}
用法:
DateTime dt = new DateTime();
String dateAsString = printDate(dt);
2)您可以使用Java 8,因为Java的API支持周月字段。
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));
这篇关于用Joda-Time获取一周的一周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!