File tree Expand file tree Collapse file tree 2 files changed +59
-3
lines changed
main/java/org/cyclonedx/util
test/java/org/cyclonedx/util Expand file tree Collapse file tree 2 files changed +59
-3
lines changed Original file line number Diff line number Diff line change 2020
2121import java .text .ParseException ;
2222import java .text .SimpleDateFormat ;
23+ import java .time .ZonedDateTime ;
24+ import java .time .format .DateTimeFormatter ;
25+ import java .time .format .DateTimeParseException ;
2326import java .util .Date ;
2427
2528@ SuppressWarnings ("unused" )
2629public final class TimestampUtils {
27- private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ssX " );
30+ private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter . ofPattern ("yyyy-MM-dd'T'HH:mm:ss[.SSS][XXX] " );
2831
2932 private TimestampUtils () {}
3033
3134 public static Date parseTimestamp (String text ) {
3235 try {
33- return DATE_FORMAT .parse (text );
34- } catch (ParseException | NullPointerException e ) {
36+ ZonedDateTime zdt = ZonedDateTime .parse (text , DATE_FORMAT );
37+ return Date .from (zdt .toInstant ());
38+ } catch (DateTimeParseException | NullPointerException e ) {
3539 return null ;
3640 }
3741 }
Original file line number Diff line number Diff line change 1+ package org .cyclonedx .util ;
2+
3+ import java .util .Date ;
4+
5+ import org .junit .jupiter .api .Test ;
6+
7+ import static org .junit .jupiter .api .Assertions .assertNotNull ;
8+ import static org .junit .jupiter .api .Assertions .assertNull ;
9+
10+ public class TimestampUtilsTest
11+ {
12+ @ Test
13+ public void testParseTimestampValid () {
14+ String validTimestamp = "2023-10-01T12:34:56.789+00:00" ;
15+ Date date = TimestampUtils .parseTimestamp (validTimestamp );
16+ assertNotNull (date );
17+ }
18+
19+ @ Test
20+ public void testParseTimestampWithZ () {
21+ String validTimestampWithZ = "2021-01-01T00:00:00.000Z" ;
22+ Date date = TimestampUtils .parseTimestamp (validTimestampWithZ );
23+ assertNotNull (date );
24+ }
25+
26+ @ Test
27+ public void testParseTimestampValidWithoutMilliseconds () {
28+ String validTimestamp = "2023-10-01T12:34:56+00:00" ;
29+ Date date = TimestampUtils .parseTimestamp (validTimestamp );
30+ assertNotNull (date );
31+ }
32+
33+ @ Test
34+ public void testParseTimestampInvalid () {
35+ String invalidTimestamp = "invalid-timestamp" ;
36+ Date date = TimestampUtils .parseTimestamp (invalidTimestamp );
37+ assertNull (date );
38+ }
39+
40+ @ Test
41+ public void testParseTimestampNull () {
42+ Date date = TimestampUtils .parseTimestamp (null );
43+ assertNull (date );
44+ }
45+
46+ @ Test
47+ public void testParseTimestampEmpty () {
48+ String emptyTimestamp = "" ;
49+ Date date = TimestampUtils .parseTimestamp (emptyTimestamp );
50+ assertNull (date );
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments