java获取当月第一天和最后一天,当年第一天和最后一天,上个月第一天和最后一天,去年第一天和最后一天,并用Long类型时间戳表示结果
时间: 2024-06-15 17:08:24 浏览: 138
Java实现获取某年某月第一天/最后一天的方法
5星 · 资源好评率100%
要获取Java中的日期信息,可以使用`java.util.Calendar`类或者`java.time.LocalDate`类。下面是使用`java.util.Calendar`类的示例代码来获取所需的日期信息,并将结果转换为Long类型的时间戳表示:
```java
import java.util.Calendar;
public class DateUtils {
public static void main(String[] args) {
// 获取当前日期
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始,需要加1
int day = calendar.get(Calendar.DAY_OF_MONTH);
// 获取当月第一天和最后一天
calendar.set(Calendar.DAY_OF_MONTH, 1);
long firstDayOfMonth = calendar.getTimeInMillis();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
long lastDayOfMonth = calendar.getTimeInMillis();
// 获取当年第一天和最后一天
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
long firstDayOfYear = calendar.getTimeInMillis();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
long lastDayOfYear = calendar.getTimeInMillis();
// 获取上个月第一天和最后一天
if (month == 1) {
calendar.set(Calendar.YEAR, year - 1);
calendar.set(Calendar.MONTH, 11);
} else {
calendar.set(Calendar.MONTH, month - 2);
}
calendar.set(Calendar.DAY_OF_MONTH, 1);
long firstDayOfLastMonth = calendar.getTimeInMillis();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
long lastDayOfLastMonth = calendar.getTimeInMillis();
// 获取去年第一天和最后一天
calendar.set(Calendar.YEAR, year - 1);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
long firstDayOfLastYear = calendar.getTimeInMillis();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
long lastDayOfLastYear = calendar.getTimeInMillis();
// 输出结果
System.out.println("当月第一天:" + firstDayOfMonth);
System.out.println("当月最后一天:" + lastDayOfMonth);
System.out.println("当年第一天:" + firstDayOfYear);
System.out.println("当年最后一天:" + lastDayOfYear);
System.out.println("上个月第一天:" + firstDayOfLastMonth);
System.out.println("上个月最后一天:" + lastDayOfLastMonth);
System.out.println("去年第一天:" + firstDayOfLastYear);
System.out.println("去年最后一天:" + lastDayOfLastYear);
}
}
```
阅读全文