问题描述
我需要检查给定的日期是否在当月,我编写了以下代码,但是IDE提醒我 getMonth()
和 getYear()
方法已过时.我想知道如何在较新的Java 7或Java 8中执行相同的操作.
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.
private boolean inCurrentMonth(Date givenDate) {
Date today = new Date();
return givenDate.getMonth() == today.getMonth() && givenDate.getYear() == today.getYear();
}
推荐答案
时区
其他答案忽略了时区的关键问题.巴黎比蒙特利尔早到了新的一天.因此,在同一时刻,日期是不同的,明天"在巴黎,而昨天"在蒙特利尔.
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.
与Java捆绑在一起的java.util.Date和.Calendar类非常麻烦,令人困惑和有缺陷.避免他们.
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them.
请改为使用 Joda-Time 库或Java 8中的java.time包(受Joda-Time启发).
Instead use either Joda-Time library or the java.time package in Java 8 (inspired by Joda-Time).
以下是Joda-Time 2.5中的示例代码.
Here is example code in 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.
}
要获得更通用的解决方案以查看某个时刻是否落在任何时间范围内(而不仅仅是一个月),请在StackOverflow中搜索"joda","interval"和"contain".
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".
这篇关于Java:检查指定日期是否在当月内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!