1 package fr.ifremer.quadrige3.core.dao.technical;
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 import org.apache.commons.lang3.StringUtils;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 import java.sql.Timestamp;
31 import java.time.*;
32 import java.time.format.DateTimeFormatter;
33 import java.time.format.DateTimeParseException;
34 import java.util.Date;
35 import java.util.TimeZone;
36
37
38
39
40 public class Times {
41
42
43
44
45 private static final DateTimeFormatter FILE_SUFFIX_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss");
46
47
48
49
50 private static final Log LOG = LogFactory.getLog(Times.class);
51
52
53
54
55 private static final DateTimeFormatter HOUR_MINUTE_FORMAT = DateTimeFormatter.ofPattern("HH:mm");
56
57
58
59
60
61
62
63 public static String secondsToString(final Integer seconds) {
64 if (seconds == null) return null;
65 return LocalTime.ofSecondOfDay(seconds).format(HOUR_MINUTE_FORMAT);
66 }
67
68
69
70
71
72
73
74 public static Integer stringToSeconds(final String string) throws DateTimeParseException {
75 if (StringUtils.isBlank(string)) return null;
76 return LocalTime.parse(string, HOUR_MINUTE_FORMAT).toSecondOfDay();
77 }
78
79
80
81
82
83
84
85 public static Date secondsToDate(final Integer seconds) {
86 if (seconds == null) return null;
87 return Dates.convertToDate(LocalDate.now().atTime(LocalTime.ofSecondOfDay(seconds)), TimeZone.getTimeZone(ZoneOffset.UTC));
88 }
89
90
91
92
93
94
95
96 public static Integer dateToSeconds(final Date date) {
97 if (date == null) return null;
98 return Dates.convertToLocalDateTime(date, TimeZone.getTimeZone(ZoneOffset.UTC)).toLocalTime().toSecondOfDay();
99 }
100
101
102
103
104
105
106
107 public static String durationToString(long millis) {
108 return Duration.ofMillis(millis).toString()
109 .substring(2)
110 .replaceAll("(\\d[HMS])(?!$)", "$1 ")
111 .toLowerCase();
112 }
113
114
115
116
117
118
119
120
121
122 public static Timestamp getTimestampOrNull(Date date) {
123 return date == null ? null : new Timestamp(date.getTime());
124 }
125
126 public static String getFileSuffix() {
127 return getFileSuffix(LocalDateTime.now());
128 }
129
130 public static String getFileSuffix(LocalDateTime localDateTime) {
131 return localDateTime.format(FILE_SUFFIX_DATE_FORMAT);
132 }
133 }