在 Java 8 中根据 LocalDate.now() 获取一周的第一天的日期 [英] Get date of first day of week based on LocalDate.now() in Java 8

查看:95
本文介绍了在 Java 8 中根据 LocalDate.now() 获取一周的第一天的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据 LocalDate.now() 获取一周的第一天的日期.JodaTime 可以实现以下功能,但似乎已从 Java 8 中的新 Date API 中删除.

I would like the get the date of the first day of the week based on LocalDate.now(). The following was possible with JodaTime, but seems to be removed from the new Date API in Java 8.

LocalDate now = LocalDate.now();
System.out.println(now.withDayOfWeek(DateTimeConstants.MONDAY));

我无法调用withDayOfWeek()",因为它不存在.

I can not call 'withDayOfWeek()', because it does not exist.

所以我的问题是:如何根据某个 LocalDate 获取一周的第一天的日期?

So my question is: How to get the date of the first day of the week based on some LocalDate?

推荐答案

请注意,表达式 System.out.println(now.with(DayOfWeek.MONDAY)) 在使用时与语言环境无关ISO-8601,因此它总是向后跳到上一个星期一(或者在日期已经指向星期一的情况下停留在星期一).

Note that the expression System.out.println(now.with(DayOfWeek.MONDAY)) is locale-independent as it uses ISO-8601, therefore it always jumps backwards to last Monday (or stays on Monday in case date points to Monday already).

因此,在美国或其他一些国家/地区 - 一周从周日开始 - 它可能不会像您预期的那样工作 - now.with(DayOfWeek.MONDAY) 不会向前跳跃 到星期一,以防日期指向星期日.

As such in US or some other countries - where week starts on Sunday - it may not work as you would expect - now.with(DayOfWeek.MONDAY) will not jump forward to Monday, in case date points to Sunday.

如果您需要解决这些问题,最好使用本地化字段 WeekFields.dayOfWeek():

In case you need to address these concerns, it is better to use the localized field WeekFields.dayOfWeek():

LocalDate now = LocalDate.now();
TemporalField fieldISO = WeekFields.of(Locale.FRANCE).dayOfWeek();
System.out.println(now.with(fieldISO, 1)); // 2015-02-09 (Monday)

TemporalField fieldUS = WeekFields.of(Locale.US).dayOfWeek();
System.out.println(now.with(fieldUS, 1)); // 2015-02-08 (Sunday)

由于以下评论而产生的另一个示例:

Another example due to comments below:

LocalDate ld = LocalDate.of(2017, 8, 18); // Friday as original date

System.out.println(
    ld.with(DayOfWeek.SUNDAY)); // 2017-08-20 (2 days later according to ISO)

// Now let's again set the date to Sunday, but this time in a localized way...
// the method dayOfWeek() uses localized numbering (Sunday = 1 in US and = 7 in France)

System.out.println(ld.with(WeekFields.of(Locale.US).dayOfWeek(), 1L)); // 2017-08-13
System.out.println(ld.with(WeekFields.of(Locale.FRANCE).dayOfWeek(), 7L)); // 2017-08-20

美国的例子很清楚地表明,居住在美国的人会希望去最后一个星期天而不是下一个星期天,因为星期天在美国被视为一周的第一天.简单的基于 ISO 的表达式 with(DayOfWeek.SUNDAY) 忽略了这个本地化问题.

The US-example makes pretty clear that someone residing in US would expect to go to last and not to next Sunday because Sunday is considered as first day of week in US. The simple ISO-based expression with(DayOfWeek.SUNDAY) ignores this localization issue.

这篇关于在 Java 8 中根据 LocalDate.now() 获取一周的第一天的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆