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

查看:7831
本文介绍了根据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)) 与locale无关,因为它使用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

美国的例子很清楚,居住在美国的人会期待因为周日在美国被视为一周的第一天,所以要到最后而不是下周日。带有(DayOfWeek.SUNDAY)的简单的基于ISO的表达式忽略了这个本地化问题。

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天全站免登陆