gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:03:55 28 4
gpt4 key购买 nike

我需要检查给定日期是否在当前月份,我编写了以下代码,但 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();
}

最佳答案

//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
}
}

关于Java:检查给定日期是否在当前月份内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26824020/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com