我需要检查给定日期是否属于当前月份,并且我编写了以下代码,但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();
}
答案 0 :(得分:8)
//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
}
}
答案 1 :(得分:7)
使用新的java.time API(tutorial)有几种方法可以做到这一点。你可以使用.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));
为了更好的可重用性,您还可以将此代码重构为"时间查询":
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
答案 2 :(得分:6)
其他答案忽略了时区的关键问题。巴黎的新日早些时候比蒙特利尔更新。因此,在同一时刻,日期不同,巴黎的“明天”和蒙特利尔的“昨天”。
与Java捆绑在一起的java.util.Date和.Calendar类是众所周知的麻烦,令人困惑和有缺陷的。避免他们。
而是在Java 8中使用Joda-Time库或java.time包(受Joda-Time启发)。
以下是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”和“contains”。
答案 3 :(得分:4)
据我所知,Calendar类及其派生的所有内容都使用get()返回日期。请参阅documentation for this class。这里还有一个来自here的例子:
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);
输出
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
我认为它被替换了,因为新方法使用单个函数提供了更简单的处理,这更容易记住。
答案 4 :(得分:0)
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));
}
请注意,此方法适用于同时具有月份和日期部分(LocalDate
,ZonedDateTime
等)的Java 8时间类中的任何一种,而不仅限于LocalDateTime