[英]Create LocalDate from Calendar Week Information
Given: 鉴于:
Needed: 需要:
A transformation f of those Infos into a LocalDate Object so that 将这些信息转换为LocalDate对象,以便
assertEquals(LocalDate.of(2019,1,6), f(2019,1,SUNDAY))
What I tried 我尝试了什么
I did not find a way with java.time.* to create a Date from an Info like "The Sunday of the first calender week in 2019". 我找不到用java.time。*从信息中创建日期的方法,例如“ 2019年第一个日历周的星期日”。 I found that the old java.util.Calendar class had a setWeekDate() function that could be usefull.
我发现旧的java.util.Calendar类具有可能有用的setWeekDate()函数。 But the following code caused an Exception:
但是以下代码导致了异常:
...
Calendar c = Calendar.getInstance();
c.setWeekDate(2019, 1, Calendar.MONDAY);
c.setTimeZone(TimeZone.getDefault());
return LocalDate.from(c.toInstant());
java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 2018-01-08T20:03:55.602Z of type java.time.Instant
at java.time.LocalDate.from(LocalDate.java:379)
at ...
Check ChronoField or IsoFields for a suitable way to get week for the calendar system that you want to use. 检查ChronoField或IsoFields以获取获取您要使用的日历系统星期的合适方法。
LocalDate
object that is used as "base" value should have a week value of the expected year. 用作“基础”值的
LocalDate
对象应具有预期年份的星期值。
int year = 2019;
int weekNumber = 1;
LocalDate localDate = LocalDate.of(year, 2, 1)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, weekNumber)
.with(ChronoField.DAY_OF_WEEK, DayOfWeek.SUNDAY.getValue());
Selecting first date is meaningful. 选择第一个日期是有意义的。 Using
LocalDate.of(year, 1, 1)
would give a day that can belong to last week of the previous year, same goes for LocalDate.now()
but only for given period of time. 使用
LocalDate.of(year, 1, 1)
将给出可以属于上一年最后一周的一天, LocalDate.now()
也是如此,但仅在给定的时间段内。
LocalDate.of(2017, 1, 1)
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
.with(ChronoField.DAY_OF_WEEK, DayOfWeek.SUNDAY.getValue());
// 2016-07-03
LocalDate.of(2017, 1, 1).get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
// 52
So jumping from week 52 to week 26 would give date of 2016-07-03 because date is calculated by subtracking time between weeks 52 and 26. 因此,从第52周跳到第26周将给出日期为2016-07-03,因为日期是通过第52周到第26周之间的子跟踪时间计算得出的。
Also see answer here for more discussion about withYear
: Unexpected date calculation result 另请参见此处的答案以获取有关
withYear
更多讨论: 意外的日期计算结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.