Java:检查给定日期是否在当月内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26824020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:21:00  来源:igfitidea点击:

Java: check if a given date is within current month

javadatejava-timejava.util.date

提问by TonyGW

I need to check if a given date falls in the current month, and I wrote the following code, but the IDE reminded me that the getMonth()and getYear()methods are obsolete. I was wondering how to do the same thing in newer Java 7 or Java 8.

我需要检查给定日期是否在当月,我编写了以下代码,但 IDE 提醒我getMonth()getYear()方法已过时。我想知道如何在较新的 Java 7 或 Java 8 中做同样的事情。

private boolean inCurrentMonth(Date givenDate) {
    Date today = new Date();

    return givenDate.getMonth() == today.getMonth() && givenDate.getYear() == today.getYear();
}

采纳答案by Basil Bourque

Time Zone

时区

The other answers ignore the crucial issue of time zone. A new day dawns earlier in Paris than in Montréal. So at the same simultaneous moment, the dates are different, "tomorrow" in Paris while "yesterday" in Montréal.

其他答案忽略了时区的关键问题。新的一天在巴黎比在蒙特利尔更早开始。所以在同一时刻,日期是不同的,巴黎的“明天”和蒙特利尔的“昨天”。

Joda-Time

乔达时间

The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them.

与 Java 捆绑在一起的 java.util.Date 和 .Calendar 类是出了名的麻烦、混乱和有缺陷。避开它们。

Instead use either Joda-Timelibrary or the java.time package in Java 8 (inspired by Joda-Time).

而是使用Java 8 中的Joda-Time库或 java.time 包(受 Joda-Time 启发)。

Here is example code in Joda-Time 2.5.

这是 Joda-Time 2.5 中的示例代码。

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( yourJUDate, zone );  // Convert java.util.Date to Joda-Time, and assign time zone to adjust.
DateTime now = DateTime.now( zone );
// Now see if the month and year match.
if ( ( dateTime.getMonthOfYear() == now.getMonthOfYear() ) && ( dateTime.getYear() == now.getYear() ) ) {
    // You have a hit.
}

For a more general solution to see if a moment falls within any span of time (not just a month), search StackOverflow for "joda" and "interval" and "contain".

要查看某个时刻是否属于任何时间跨度(不仅仅是一个月)的更通用解决方案,请在 StackOverflow 中搜索“joda”、“interval”和“contain”。

回答by rbaleksandar

As far as I know the Calendar class and all derived from it return the date using the get(). See the documentation for this class. Also here is an example taken from here:

据我所知,Calendar 类及其派生的所有类都使用 get() 返回日期。请参阅此类文档。另外这里是从这里采取的一个例子:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");    
Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);

int year       = calendar.get(Calendar.YEAR);
int month      = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); 
int dayOfWeek  = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);

int hour       = calendar.get(Calendar.HOUR);        // 12 hour clock
int hourOfDay  = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute     = calendar.get(Calendar.MINUTE);
int second     = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);

System.out.println(sdf.format(calendar.getTime()));

System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);

System.out.println("hour \t\t: " + hour);
System.out.println("hourOfDay \t: " + hourOfDay);
System.out.println("minute \t\t: " + minute);
System.out.println("second \t\t: " + second);
System.out.println("millisecond \t: " + millisecond);

which outputs

哪个输出

2013 Feb 28 13:24:56
year        : 2013
month       : 1
dayOfMonth  : 28
dayOfWeek   : 5
weekOfYear  : 9
weekOfMonth : 5
hour        : 1
hourOfDay   : 13
minute      : 24
second      : 56
millisecond : 0

I think it was replaced because the new way offers a much simpler handling using a single function, which is much easier to remember.

我认为它被替换是因为新方法使用单个函数提供了更简单的处理,这更容易记住。

回答by Yusuf Kapasi

//Create 2 instances of Calendar
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

//set the given date in one of the instance and current date in the other
cal1.setTime(givenDate);
cal2.setTime(new Date());

//now compare the dates using methods on Calendar
if(cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
    if(cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) {
        // the date falls in current month
    }
}

回答by viktor

java.time (Java 8)

java.time (Java 8)

There are several ways to do it with the new java.timeAPI (tutorial). You can do it using .get(ChronoField.XY), but I think this is prettier:

有几种方法可以使用新的java.timeAPI(教程)来实现。您可以使用.get(ChronoField.XY),但我认为这更漂亮:

Instant given = givenDate.toInstant();
Instant ref = Instant.now();
return Month.from(given) == Month.from(ref) && Year.from(given).equals(Year.from(ref));

For better re-usability you can also refactor this code to "temporal query":

为了更好的重用性,您还可以将此代码重构为“临时查询”:

public class TemporalQueries {
  //TemporalQuery<R> { R queryFrom(TemporalAccessor temporal) }
  public static Boolean isCurrentMonth(TemporalAccessor temporal) {
         Instant ref = Instant.now();
         return Month.from(temporal) == Month.from(ref) && Year.from(temporal).equals(Year.from(ref));           
  }
}

Boolean result = givenDate.toInstant().query(TemporalQueries::isCurrentMonth); //Lambda using method reference

回答by M. Justin

java.time (Java 8)

java.time (Java 8)

Java 8 provides the YearMonthclass which represents a given month within a given year (e.g. January 2018). This can be used to compare against the YearMonthof the given date.

Java 8 提供了YearMonth表示给定年份(例如 2018 年 1 月)中给定月份的类。这可用于YearMonth与给定日期的进行比较。

private boolean inCurrentMonth(Date givenDate) {
    ZoneId timeZone = ZoneOffset.UTC; // Use whichever time zone makes sense for your use case
    LocalDateTime givenLocalDateTime = LocalDateTime.ofInstant(givenDate.toInstant(), timeZone);

    YearMonth currentMonth = YearMonth.now(timeZone);

    return currentMonth.equals(YearMonth.from(givenLocalDateTime));
}

Note that this approach will work for any of the Java 8 time classes that have both a month and a date part (LocalDate, ZonedDateTime, etc.) and not just LocalDateTime.

注意,这种方法适用于任何具有两个月份和日期部分(在Java 8次类的工作LocalDateZonedDateTime等等),而不是只LocalDateTime