检索上周一和周五日期的最佳方法是什么

2022-01-11 00:00:00 datetime date calendar java

我需要获取上周星期一和星期五的日期.为此,我得到本周星期一的日期并减去 7 天.这给了我上周星期一的日期.

要获得星期五的日期,我必须添加 4.这让我有点困惑,因为出于某种原因,一周的第一天是星期日,而不是英国的星期一.

无论如何,这就是我获取日期的方式.

//获取最后一个 MON & 的日期周五日历 cal = Calendar.getInstance();cal.setTime(日期);cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);cal.add(Calendar.DAY_OF_WEEK, -7);cal.set(Calendar.HOUR_OF_DAY,0);cal.set(Calendar.MINUTE,0);cal.set(Calendar.SECOND,0);cal.set(Calendar.MILLISECOND,0);//获取星期五的日期cal.add(Calendar.DAY_OF_WEEK, 4);cal.set(Calendar.HOUR_OF_DAY,23);cal.set(Calendar.MINUTE,59);cal.set(Calendar.SECOND,59);cal.set(Calendar.MILLISECOND,0);

上述方法有效,但如果逻辑有任何问题,我很感兴趣.IE.它适用于二月、闰年等吗?

欢迎提出更好的解决方案/方法.

谢谢

解决方案

tl;dr

<块引用>

获取上周周一和周五的日期

LocalDate//仅表示日期,没有时间,也没有时区或偏移量..now//捕获通过某个地区(时区)的人们使用的挂钟时间看到的当前日期.(ZoneId.of("美国/蒙特利尔"))//返回一个 `LocalDate` 对象..with//移动到另一个日期.(TemporalAdjusters.previous( DayOfWeek.MONDAY )//返回 `TemporalAdjuster` 接口的实现.)//返回另一个 `LocalDate` 对象,与我们原来的 `LocalDate` 对象分开且不同.根据不可变对象设计模式.

避免使用旧的日期时间类

其他答案使用麻烦的旧日期时间类,现在已被 java.time 问题所取代.

本地日期

LocalDate 类表示没有时间和时区的仅日期值.

时区对于确定日期至关重要.对于任何给定的时刻,日期在全球范围内因区域而异.例如,Paris France 午夜过后几分钟是新的一天,但仍然是昨天"在 蒙特利尔魁北克.

ZoneId z = ZoneId.of(美国/蒙特利尔");今天的 LocalDate = LocalDate.now(z);

TemporalAdjuster

TemporalAdjuster 界面提供从一个日期时间值移动到另一个日期时间值的调整.在 TemporalAdjusters 类(注意复数s").previous 调整器从 DayOfWeek 枚举.

该问题并未准确定义上周".最后七天?标准的周一至周日时段?本地化周,例如美国的周日至周六?今天的前一周还是包括今天的部分星期?

我会假设前 7 天是预定的.

LocalDate previousMonday = today.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));LocalDate previousFriday = today.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));

顺便说一句,如果您想考虑初始日期(如果它恰好已经是所需的星期几),请使用备用 TemporalAdjuster 实现:previousOrSamenextOrSame.

<小时>

关于java.time

java.time 框架内置于 Java 8 及更高版本中.这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date, 日历, &SimpleDateFormat.

Joda-Time 项目,现在在 维护模式,建议迁移到 java.time 类.

要了解更多信息,请参阅 Oracle 教程.并在 Stack Overflow 上搜索许多示例和解释.规范是 JSR 310.

您可以直接与您的数据库交换 java.time 对象.使用符合 JDBC 驱动程序jeps/170" rel="noreferrer">JDBC 4.2 或更高版本.不需要字符串,不需要 java.sql.* 类.

从哪里获得 java.time 类?

  • Java SE 8, Java SE 9 及更高版本
    • 内置.
    • 标准 Java API 的一部分,带有捆绑实现.
    • Java 9 添加了一些小功能和修复.
  • Java SE 6 和 Java SE 7
    • 大部分 java.time 功能都向后移植到 Java 6 &7 在 ThreeTen-Backport.
  • Android
    • java.time 类的 Android 捆绑包实现的更高版本.
    • 对于早期的 Android (<26),ThreeTenABP 项目适应ThreeTen-Backport(如上所述).请参阅如何使用 ThreeTenABP….

ThreeTen-Extra 项目扩展了 java.time额外的课程.该项目是未来可能添加到 java.time 的试验场.您可以在这里找到一些有用的类,例如 Interval, YearWeek, YearQuarter 和 更多.

I need to get the dates for Monday and Friday last week. To do this, i am getting the date of Monday this week and subtracting 7 days. This gives me the date for Monday last week.

To get the date for Friday i have to add 4. This confused me a bit because for some reason the first day of the week is Sunday as opposed to Monday here in the UK.

Anyway, here is how i am getting the dates.

            // Get the dates for last MON & FRI
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.add(Calendar.DAY_OF_WEEK, -7);

        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        cal.set(Calendar.MILLISECOND,0);

        // Get the date on Friday
        cal.add(Calendar.DAY_OF_WEEK, 4);

        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        cal.set(Calendar.MILLISECOND,0);

The above works but i am interested if there is anything wrong with the logic. I.e. will it work for Februarys, leap years etc.

Feel free to suggest a better solution/approach.

Thanks

解决方案

tl;dr

get the dates for Monday and Friday last week

LocalDate                                           // Represent a date only, without a time-of-day, and without a time zone or offset.
.now                                                // Capture the current date as seen through the wall-clock time used by the people of a certain region (a time zone). 
( 
    ZoneId.of( "America/Montreal" ) 
)                                                   // Returns a `LocalDate` object.
.with                                               // Move to another date.
( 
    TemporalAdjusters.previous( DayOfWeek.MONDAY )  // Returns an implementation of the `TemporalAdjuster` interface.
)                                                   // Returns another `LocalDate` object, separate and distinct from our original `LocalDate` object. Per the immutable objects design pattern. 

Avoid legacy date-time classes

The other Answers use the troublesome old legacy date-time classes now supplanted by the java.time questions.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still "yesterday" in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

TemporalAdjuster

The TemporalAdjuster interface provides for adjustments to move from one date-time value to another. Find handy implementations in the TemporalAdjusters class (note the plural 's'). The previous adjuster finds any specified object from the DayOfWeek enum.

The Question does not exactly define "last week". Last seven days? Standard Monday-Sunday period? Localized week, such as Sunday-Saturday in the United States? The week prior to today’s week or including today’s partial week?

I will assume the prior seven days were intended.

LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) ) ;
LocalDate previousFriday = today.with( TemporalAdjusters.previous( DayOfWeek.FRIDAY ) ) ;

By the way, if you want to consider the initial date if it happens to already be the desired day-of-week, use alternate TemporalAdjuster implementations: previousOrSame or nextOrSame.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

相关文章