# 常见又易错点
# 又有兄弟因为用YYYY-MM-dd 被锤了
/**
* 24小时时间格式化字符串
*/
public static final String DATE_TIME_FORMAT_24 = "yyyy-MM-dd HH:mm:ss";
/**
* 根据本周所在年份格式化时间,注意:YYYY
*/
public static final String DATE_TIME_FORMAT_Y_24 = "YYYY-MM-dd HH:mm:ss";
/**
* 测试YYYY与yyyy
*/
@Test
public void testYy() {
LocalDateTime nowLocal = LocalDateTime.now();
Date nowDate = new Date();
System.out.println("YYYY" + nowLocal.format(findDateTimeFormatter(GlobalConstants.DATE_TIME_FORMAT_Y_24)));
System.out.println("yyyy" + nowLocal.format(findDateTimeFormatter(GlobalConstants.DATE_TIME_FORMAT_24)));
System.out.println("Date YYYY" + findSimpleDateFormat(GlobalConstants.DATE_TIME_FORMAT_Y_24).format(nowDate));
System.out.println("Date yyyy" + findSimpleDateFormat(GlobalConstants.DATE_TIME_FORMAT_24).format(nowDate));
}
// YYYY2021-12-30 09:37:31
// yyyy2020-12-30 09:37:31
// Date YYYY2021-12-30 09:37:31
// Date yyyy2020-12-30 09:37:31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
YYYY
因为YYYY是week-based-year,表示:当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,那么这周就算入下一年。
# 最大时间入库时有时变成第二天0点
如下:
LocalDateTime now1 = LocalDateTime.now().withHout(23).withMinute(59).withSecond(59);
/**
* The maximum supported {@code LocalTime}, '23:59:59.999999999'.
* This is the time just before midnight at the end of the day.
*/
LocalDateTime now2 = LocalDateTime.now().with(LocalTime.MAX);
// 此时间入库可能因为【毫秒】比较大的原因,数据库种的时间会变成【第二天的00:00:00】
/**
* The time of midnight at the start of the day, '00:00'.
*/
// public static final LocalTime MIDNIGHT;
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
所以针对时间跨天到次日的问题,最大时间最好采用如下方式:
LocalTime time = LocalTime.of(23, 59, 59);
// return new LocalTime(hour, minute, second, 0);
// 最后一个参数为:nanoOfSecond,纳秒
1
2
3
2
3