1.获取常用日期、手动设置日期
// 获取当前日期
LocalDate currentDate = LocalDate.now();
//转化为Date格式
Date currentDate1 = java.sql.Date.valueOf(currentDate);
// 获取上个月的日期
LocalDate previousMonth = currentDate.minusMonths(1);
// 获取年份和月份
YearMonth lastMonthYearMonth = YearMonth.from(previousMonth );
int lastMonthYear = lastMonthYearMonth.getYear();
int lastMonthMonth = lastMonthYearMonth.getMonthValue();
//或
int year = previousMonth.getYear();
int month = previousMonth.getMonthValue();
//获取一个月最后一天
int lastDayOfThisMonthDay = YearMonth.from(currentDate).atEndOfMonth().getDayOfMonth();
//手动设置一个日期
Date startDate = new Date(year- 1900, month , 1, 0, 0, 0);
Date endDate = new Date(lastMonthYear - 1900, lastMonthMonth, lastDayOfThisMonthDay, 23, 59, 59);
2.获取日期时间段列表
List<Date> dateList = new ArrayList<>();
dateList.add(currentDate1);
// 获取当天至前90天的日期
for (int i = 1; i <= 90; i++) {
LocalDate date = currentDate.minusDays(i);
Date javaDate = java.sql.Date.valueOf(date);
dateList.add(javaDate);
}
//截取日期时间段
dateList.subList(1,90);
3.将数据库查询到的日期转换为固定字符串
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.format(record.getClickDate());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = currentDate.format(formatter);
4.查询条件中查询与某个日期相等(DATE_FORMAT字段为Date类型,formattedDate为3.中转换后的字符串)
LambdaQueryWrapper<FunctionClickRecord> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.apply("DATE_FORMAT(click_date, '%Y-%m-%d') = {0}", formattedDate);
5.查询日期范围内数据(CreateDate字段为Date格式)
LambdaQueryWrapper<PerformanceDetectionTaskAssignmentDetailsInfo> queryWrapper =Wrappers.lambdaQuery();
queryWrapper.between(PerformanceDetectionTaskAssignmentDetailsInfo::getCreateDate,startDate,endDate);
5.获取缓存过期时间
/**
* 根据往后推迟的时间返回过期时间戳
*
* @param addTime 比当前时间多少分钟后过期
* @return
*/
private static long getExpirationTime(Long addTime) {
long minutesToAdd = addTime; // 增加**分钟
LocalDateTime now = LocalDateTime.now();
LocalDateTime futureDateTime = now.plus(minutesToAdd, ChronoUnit.MINUTES);
// 获取将来时间的时间戳(以秒为单位)
long futureTimestampInSeconds = futureDateTime.toEpochSecond(java.time.ZoneOffset.UTC);
return futureTimestampInSeconds;
}
6.时间戳转为日期字符串输出
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//时间戳转换为时间
long time = projectStateRecord.getGmtModified().getTime();
Date date = new Date(time);
returnReasonVO.setBackDate(sdf.format(date));