java8的时间api很好用,但有的场景用Calendar也是很合适的
/**
* 从当前时间获取上个月的第一天和最后一天
*/
private void getPreMonthDate(String startDate) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = getPreMonth(startDate);
//获取某月最小天数
int firstDay = c.getActualMinimum(Calendar.DAY_OF_MONTH);
//设置日历中月份的最小天数
c.set(Calendar.DAY_OF_MONTH, firstDay);
// 上个月第一天
String startTime = format.format(c.getTime());
Calendar c2 = getPreMonth(startDate);
int lastDay = c2.getActualMaximum(Calendar.DAY_OF_MONTH);
c2.set(Calendar.DAY_OF_MONTH, lastDay);
String endTime = format.format(c2.getTime());
}
/**
* 从当前时间"yyyy-MM-dd"格式获取上个月的时间
*/
private Calendar getPreMonth(String startDate) throws Exception{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date date = format.parse(startDate);
c.setTime(date);
c.add(Calendar.MONTH, -1);
return c;
}
获取上周的时间也是一个道理
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date date = format.parse("2020-05-01");
c.setTime(date);
c.add(Calendar.DATE, -7);
format.format(c.getTime());
获取当前星期内星期*的date
LocalDate currentDate = LocalDate.now();
// 获取本周星期*的date
LocalDate mondayLocalDate = currentDate.with(DayOfWeek.MONDAY);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
mondayLocalDate.format(dateTimeFormatter);
// 获取上周内 「星期*」的 date
LocalDate previousDate = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
获取当天0点10位时间戳
Long time = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).toEpochSecond(ZoneOffset.of("+8"));
String format = String.format("local:time:%s", time);
根据时间戳和日期格式转化成日期字符串
String date =getDateStringByTimestamp(1234567890, "yyyyMMdd");
public static String getDateStringByTimestamp(Integer timestamp, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return formatter.format(LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneOffset.of("+8")));
}
获取当月第一天的时间
//获取当月第一天
public static LocalDate getCurMonthFirstDay() {
LocalDate currentDate = LocalDate.now();
return currentDate.with(TemporalAdjusters.firstDayOfMonth());
}