不知道有没有遇到过那种在项目上需要对时间进行操作然后查了半天没找到想要的情况?这里总结了一下一些常规的Java DateTime相关的操作。
参考了这个网页:
https://howtodoinjava.com/java/date-time/localdate-localdatetime-conversions/
- 格式
以LocalDateTime为例,时间的格式为"yyyy-MM-dd HH:mm:ss"。打印出来看看!
LocalDateTime now = LocalDateTime.now(); System.out.println(LocalDateTime.now()); 结果为:2021-11-08T11:38:54.560
- String -> LocalDateTime
parse(CharSequence text, DateTimeFormatter formatter)
第一个参数为 需要转换的字符串, 第二个参数为转换的时间格式
String strToLDT = "1995-04-05 06:06:06";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(LocalDateTime.parse("1995-04-05T06:06:06"));
LocalDateTime strTest = LocalDateTime.parse(strToLDT, formatter);
System.out.println(strTest);
separatorLine();
打印结果为:
2021-11-08 11:38:54
- LocalDateTime -> String
format(DataTimeFormatter formatter)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String toStrTest = now.format(formatter);;
System.out.println(toStrTest);
separatorLine();
打印结果为:
2021-11-08 11:44:28
- LocalDateTime -> LocalDate
//前端传入LocalDateTime,只需要年月日
LocalDate localDate = now.toLocalDate();
System.out.println(localDate);
separatorLine();
在一些统计类的业务场景中,有时候不需要用到时分秒,可以在进去mapper层之间对时间进行一次转换。
5.LocalDate->LocalDateTime
有五种方法可以完成LocalDate->LocalDateTime的转换:
比如拼凑一个时间看看:
System.out.println(localDate.atTime(5,12,50));
separatorLine();
打印结果为:
2021-11-07T05:12:50
- 获取上上个月的第一天和上个月的最后一天
LocalDate firstDayOfMonthBeforeLastMonth = now.minusMonths(2).withDayOfMonth(1).toLocalDate();
LocalDate lastDayOfMonthBeforeLastMonth = now.withDayOfMonth(1).minusDays(1).toLocalDate();
System.out.println(firstDayOfMonthBeforeLastMonth);
System.out.println(lastDayOfMonthBeforeLastMonth);
separatorLine();
打印结果为:
2021-09-01 2021-10-31
MYSQL上一些关于时间的操作:
- 计算时间差值并向上取整(timestampdiff不好用)
DATEDIFF
CEIL(AVG(DATEDIFF(redeemed_time, obtain_time) + 1))
- 取上上个月的数据和上个月的数据
PERIOD_DIFF获取时间差值
DATE_FORMAT重新转换时间格式
COUNT(IF(period_diff(date_format(now(), '%Y%m'), date_format(order_time, '%Y%m')) = 1, true, null)) as 上个月数据, COUNT(IF(period_diff(date_format(now(), '%Y%m'), date_format(order_time, '%Y%m')) = 2, true, null)) as 上上个月数据
时间能在外层处理了就在外层处理了再传到mapper层来。



