java 检查date是否在本月、本周、上周、去年 区间中
时间: 2023-10-02 10:10:15 浏览: 94
java 中List按照date排序的实现
可以使用Java的Date类和Calendar类来检查日期所属的区间。下面是实现的简单示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateChecker {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 获取当前时间
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
// 检查是否在本月
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date monthStart = calendar.getTime();
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date monthEnd = calendar.getTime();
boolean inThisMonth = today.after(monthStart) && today.before(monthEnd);
System.out.println("Is in this month: " + inThisMonth);
// 检查是否在本周
calendar.setTime(today);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
calendar.add(Calendar.DAY_OF_MONTH, -(dayOfWeek - calendar.getFirstDayOfWeek()));
Date weekStart = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = calendar.getTime();
boolean inThisWeek = today.after(weekStart) && today.before(weekEnd);
System.out.println("Is in this week: " + inThisWeek);
// 检查是否在上周
calendar.setTime(weekStart);
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date lastWeekStart = calendar.getTime();
calendar.add(Calendar.DAY_OF_MONTH, 6);
Date lastWeekEnd = calendar.getTime();
boolean inLastWeek = today.after(lastWeekStart) && today.before(lastWeekEnd);
System.out.println("Is in last week: " + inLastWeek);
// 检查是否在去年
calendar.setTime(today);
calendar.add(Calendar.YEAR, -1);
Date lastYearToday = calendar.getTime();
boolean inLastYear = today.getYear() == lastYearToday.getYear();
System.out.println("Is in last year: " + inLastYear);
}
}
```
在该示例代码中,我们做了以下事情:
1. 通过SimpleDateFormat类创建了一个格式化日期的对象df,方便输出日期字符串;
2. 通过Calendar.getInstance()方法获取当前时间的Calendar对象calendar;
3. 通过设置calendar的不同字段来计算所需区间的起止日期,并使用getTime()方法获取日期对象;
4. 使用Date类的after()和before()方法来比较日期是否在该区间内;
5. 根据比较结果输出相应的信息。
可以根据上面的示例代码,自行添加逻辑进行功能扩展。
阅读全文