MilvusTimeUtil.java
2.37 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.xly.milvus.util;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
public class MilvusTimeUtil {
public static final long NULL_TIMESTAMP = -1L;
// 多种 ISO 格式
private static final List<DateTimeFormatter> ISO_FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"), // 完整格式
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"), // 缺少秒
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH"), // 只有小时
DateTimeFormatter.ISO_LOCAL_DATE_TIME, // 标准 ISO
DateTimeFormatter.ISO_OFFSET_DATE_TIME // 带时区
);
/**
* 智能解析多种 ISO 格式
*/
public static long toTimestamp(String isoString) {
if (isoString == null || isoString.trim().isEmpty()) {
return NULL_TIMESTAMP;
}
// 尝试多种格式
for (DateTimeFormatter formatter : ISO_FORMATTERS) {
try {
LocalDateTime localDateTime = LocalDateTime.parse(isoString, formatter);
return localDateTime.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
} catch (DateTimeParseException e) {
// 继续尝试下一个格式
}
}
// 特殊处理:如果只有日期
try {
LocalDate localDate = LocalDate.parse(isoString);
return localDate.atStartOfDay(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
} catch (DateTimeParseException e) {
// 忽略
}
System.err.println("无法解析的日期格式: " + isoString);
return NULL_TIMESTAMP;
}
/**
* 补全秒部分(将缺少秒的格式补全为 :00)
*/
public static String fillSeconds(String isoString) {
if (isoString == null) return null;
// 匹配 yyyy-MM-dd'T'HH:mm 格式
if (isoString.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}")) {
return isoString + ":00";
}
// 匹配 yyyy-MM-dd'T'HH 格式
if (isoString.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}")) {
return isoString + ":00:00";
}
return isoString;
}
}