I'm aware there are several similiar questions. But mine is different in two points
java.util.*
classes only (our server currently operates only with those)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?
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.