Skip to content

Commit a69d05a

Browse files
yuluo-yxZY945
andauthored
[improve] optimize DateUtil and add test case (apache#1974)
Signed-off-by: yuluo-yx <[email protected]> Co-authored-by: 东风 <[email protected]>
1 parent ca93a65 commit a69d05a

File tree

5 files changed

+112
-19
lines changed

5 files changed

+112
-19
lines changed

alerter/src/main/java/org/apache/hertzbeat/alert/dto/GeneralCloudAlertReport.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
package org.apache.hertzbeat.alert.dto;
1919

20+
import java.util.Optional;
2021
import lombok.AllArgsConstructor;
2122
import lombok.Data;
2223
import lombok.EqualsAndHashCode;
@@ -54,10 +55,18 @@ public void refreshAlertTime() {
5455
if (StringUtils.isNotBlank(alertDateTime)) {
5556
Long timeStamp = null;
5657
if (StringUtils.isNotBlank(dateTimeFormat)) {
57-
timeStamp = DateUtil.getTimeStampFromFormat(alertDateTime, dateTimeFormat);
58+
Optional<Long> tsf = DateUtil.getTimeStampFromFormat(alertDateTime, dateTimeFormat);
59+
boolean present = tsf.isPresent();
60+
if (present) {
61+
timeStamp = tsf.get();
62+
}
5863
}
5964
if (timeStamp == null) {
60-
timeStamp = DateUtil.getTimeStampFromSomeFormats(alertDateTime);
65+
Optional<Long> tsf = DateUtil.getTimeStampFromSomeFormats(alertDateTime);
66+
boolean present = tsf.isPresent();
67+
if (present) {
68+
timeStamp = tsf.get();
69+
}
6170
}
6271
if (timeStamp != null) {
6372
setAlertTime(timeStamp);

alerter/src/main/java/org/apache/hertzbeat/alert/dto/TenCloudAlertReport.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,9 @@ public Integer getAlertDuration() {
132132

133133
@Override
134134
public long getAlertTime() {
135-
return DateUtil.getTimeStampFromFormat(getFirstOccurTime(), "yyyy-MM-dd HH:mm:ss");
135+
136+
return DateUtil.getTimeStampFromFormat(getFirstOccurTime(), "yyyy-MM-dd HH:mm:ss")
137+
.orElse(0L);
136138
}
137139

138140
@Override

alerter/src/main/java/org/apache/hertzbeat/alert/util/AlertTemplateUtil.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@
2626
* Alarm template keyword matching replacement engine tool
2727
*/
2828
@Slf4j
29-
public class AlertTemplateUtil {
29+
public final class AlertTemplateUtil {
30+
31+
private AlertTemplateUtil() {
32+
}
3033

3134
/**
3235
* Match the variable ${key}

alerter/src/main/java/org/apache/hertzbeat/alert/util/DateUtil.java

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,49 +17,67 @@
1717

1818
package org.apache.hertzbeat.alert.util;
1919

20-
import java.text.ParseException;
21-
import java.text.SimpleDateFormat;
20+
import java.time.LocalDateTime;
21+
import java.time.ZoneOffset;
22+
import java.time.format.DateTimeFormatter;
23+
import java.time.format.DateTimeFormatterBuilder;
24+
import java.util.Optional;
2225
import lombok.extern.slf4j.Slf4j;
2326

2427
/**
2528
* date time common util
2629
*/
2730
@Slf4j
28-
public class DateUtil {
31+
public final class DateUtil {
32+
33+
private DateUtil() {
34+
}
2935

3036
private static final String[] DATE_FORMATS = {
37+
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'",
3138
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
3239
"yyyy-MM-dd HH:mm:ss"
3340
};
3441

3542
/**
3643
* convert date to timestamp
3744
* @param date date
45+
* @return timestamp
3846
*/
39-
public static Long getTimeStampFromSomeFormats(String date) {
40-
SimpleDateFormat sdf;
47+
public static Optional<Long> getTimeStampFromSomeFormats(String date) {
4148
for (String dateFormat : DATE_FORMATS) {
4249
try {
43-
sdf = new SimpleDateFormat(dateFormat);
44-
return sdf.parse(date).getTime();
45-
} catch (ParseException e) {
46-
log.error(e.getMessage());
50+
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
51+
.appendPattern(dateFormat)
52+
// enable string conversion in strict mode.
53+
.parseStrict()
54+
.toFormatter();
55+
LocalDateTime time = LocalDateTime.parse(date, dateTimeFormatter);
56+
return Optional.of(time.toInstant(ZoneOffset.UTC).toEpochMilli());
57+
} catch (Exception e) {
58+
log.warn("Error parsing date '{}' with format '{}': {}",
59+
date, dateFormat, e.getMessage());
4760
}
4861
}
49-
return null;
62+
63+
log.error("Error parsing date '{}', no corresponding date format", date);
64+
return Optional.empty();
5065
}
5166

5267
/**
5368
* convert format data to timestamp
5469
*/
55-
public static Long getTimeStampFromFormat(String date, String format) {
56-
SimpleDateFormat sdf = new SimpleDateFormat(format);
70+
public static Optional<Long> getTimeStampFromFormat(String date, String format) {
5771
try {
58-
return sdf.parse(date).getTime();
72+
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
73+
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
74+
return Optional.of(dateTime.toInstant(java.time.ZoneOffset.UTC).toEpochMilli());
5975
} catch (Exception e) {
60-
log.error(e.getMessage());
76+
log.error("Error parsing date '{}' with format '{}': {}",
77+
date, format, e.getMessage());
6178
}
62-
return null;
79+
80+
return Optional.empty();
6381
}
6482

6583
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.hertzbeat.alert.util;
19+
20+
import org.junit.jupiter.api.Test;
21+
22+
import java.util.Optional;
23+
24+
import static org.junit.jupiter.api.Assertions.*;
25+
26+
/**
27+
* Test case for {@link DateUtil}
28+
*/
29+
class DateUtilTest {
30+
31+
@Test
32+
void getTimeStampFromSomeFormats() {
33+
String date = "2024-05-13";
34+
Optional<Long> actualTimestamp = DateUtil.getTimeStampFromSomeFormats(date);
35+
assertFalse(actualTimestamp.isPresent());
36+
37+
date = "2024-05-13T12:34:56.789Z";
38+
actualTimestamp = DateUtil.getTimeStampFromSomeFormats(date);
39+
assertTrue(actualTimestamp.isPresent());
40+
assertEquals(1715603696789L, actualTimestamp.get());
41+
42+
date = "2023-02-22T07:27:15.404000000Z";
43+
actualTimestamp = DateUtil.getTimeStampFromSomeFormats(date);
44+
assertTrue(actualTimestamp.isPresent());
45+
assertEquals(1677050835404L, actualTimestamp.get());
46+
}
47+
48+
@Test
49+
void getTimeStampFromFormat() {
50+
String date = "2024-05-13 10:30:00";
51+
String format = "yyyy-MM-dd HH:mm:ss";
52+
Optional<Long> actualTimestamp = DateUtil.getTimeStampFromFormat(date, format);
53+
assertTrue(actualTimestamp.isPresent());
54+
assertEquals(1715596200000L, actualTimestamp.get());
55+
56+
date = "2024-05-13";
57+
format = "yyyy-MM-dd HH:mm:ss.SSS";
58+
actualTimestamp = DateUtil.getTimeStampFromFormat(date, format);
59+
assertFalse(actualTimestamp.isPresent());
60+
}
61+
}

0 commit comments

Comments
 (0)