java获取当月第一天和最后一天,当年第一天和最后一天,上个月第一天和最后一天,去年第一天和最后一天,并用Long类型时间戳表示结果
时间: 2024-06-15 18:08:24 浏览: 155
sql日期计算SQL.pdf
要获取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);
}
}
```
阅读全文