英文:
Check if current date date is within current month
问题
我知道有几个类似的问题。但是我的问题在两个方面与之不同:
- 仅使用
java.util.*
类(我们的服务器目前仅使用这些类)。 - 我需要确定给定的日期是否在指定日期之后,或者表示同一天(通常是今天)。
这是我得到的代码:
if ((new Date().getMonth() == object.getDate().getMonth() && new Date().getYear() == object.getDate().getYear()
&& new Date().getDay() == object.getDate().getDay())
|| (new Date().after(object.getDate()) && new Date().getMonth() == object.getDate().getMonth()
&& new Date().getYear() == object.getDate().getYear()))
这段代码虽然有效,但老实说,看起来不是很优雅。有没有更好的方法来实现这个需求?
英文:
I'm aware there are several similiar questions. But mine is different in two points
- Usage of
java.util.*
classes only (our server currently operates only with those) - I need to determine whether given date is after the specified date OR represents same day (typically today)
This is what I got:
if ((new Date().getMonth() == object.getDate().getMonth() && new Date().getYear() == object.getDate().getYear()
&& new Date().getDay() == object.getDate().getDay())
|| (new Date().after(object.getDate()) && new Date().getMonth() == object.getDate().getMonth()
&& new Date().getYear() == object.getDate().getYear()))
This thing works, but let's be honest - doesn't look really elegant. Is there way to do this in prettier way?
答案1
得分: 0
如果您想使用您的解决方案,无论如何都值得对其进行优化。例如,只创建一次 new Date()
。此外,为了使代码更易读且更短,将 object.getDate()
提取为一个变量,放在所有这些比较之前。解决您问题的另一种方式可能是:
public static void main(String[] args) {
Calendar min = getMinDateOfMonth();
Calendar max = getMinDateOfMonth();
max.set(Calendar.MONTH, min.get(Calendar.MONTH) + 1);
if (min.getTime().before(object.getDate()) && max.getTime().after(object.getDate())) {
// 您在这个月内
}
}
private static Calendar getMinDateOfMonth() {
Calendar min = Calendar.getInstance();
min.set(Calendar.DAY_OF_MONTH, 1);
min.set(Calendar.HOUR, 0);
min.set(Calendar.MINUTE, 0);
min.set(Calendar.SECOND, 0);
min.set(Calendar.MILLISECOND, 0);
return min;
}
英文:
if you want to use your solution, it's anyway worth optimizing it. For example, create new Date()
only once. Also to make it more readable and shorter, extract object.getDate()
as a variable above all these comparisons. One more way to solve your problem can be:
public static void main(String[] args) {
Calendar min = getMinDateOfMonth();
Calendar max = getMinDateOfMonth();
max.set(Calendar.MONTH, min.get(Calendar.MONTH) + 1);
if (min.getTime().before(object.getDate()) && max.getTime().after(object.getDate())) {
// you're inside the month
}
}
private static Calendar getMinDateOfMonth() {
Calendar min = Calendar.getInstance();
min.set(Calendar.DAY_OF_MONTH, 1);
min.set(Calendar.HOUR, 0);
min.set(Calendar.MINUTE, 0);
min.set(Calendar.SECOND, 0);
min.set(Calendar.MILLISECOND, 0);
return min;
}
专注分享java语言的经验与见解,让所有开发者获益!
评论