1 package fr.ifremer.quadrige2.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 import org.joda.time.DateTimeConstants;
30 import org.joda.time.LocalTime;
31 import org.joda.time.chrono.ISOChronology;
32 import org.joda.time.format.DateTimeFormat;
33 import org.joda.time.format.DateTimeFormatter;
34
35 import java.util.Date;
36
37
38
39
40 public class Times {
41
42
43
44
45 public static final DateTimeFormatter FILE_SUFFIX_DATE_FORMAT = DateTimeFormat.forPattern("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 = DateTimeFormat.forPattern("HH:mm");
56
57
58
59
60
61
62
63 public static String secondsToString(final Double seconds) {
64 if (seconds == null) {
65 return null;
66 }
67
68 return toLocalTime(seconds).toString(HOUR_MINUTE_FORMAT);
69 }
70
71 private static LocalTime toLocalTime(Double seconds) {
72 return new LocalTime(seconds.intValue() * DateTimeConstants.MILLIS_PER_SECOND, ISOChronology.getInstanceUTC());
73 }
74
75
76
77
78
79
80
81 public static Double stringToSeconds(final String string) {
82 if (StringUtils.isBlank(string)) {
83 return null;
84 }
85 try {
86 return toSeconds(LocalTime.parse(string, HOUR_MINUTE_FORMAT));
87 } catch (final UnsupportedOperationException e) {
88 LOG.error("Error parsing hour", e);
89 }
90 return null;
91 }
92
93 private static Double toSeconds(LocalTime localTime) {
94 Integer seconds = localTime.getHourOfDay() * DateTimeConstants.SECONDS_PER_HOUR + localTime.getMinuteOfHour() * DateTimeConstants.SECONDS_PER_MINUTE;
95 return seconds.doubleValue();
96 }
97
98
99
100
101
102
103
104 public static Date secondsToDate(final Double seconds) {
105 if (seconds != null) {
106 return toLocalTime(seconds).toDateTimeToday().toDate();
107 }
108 return null;
109 }
110
111
112
113
114
115
116
117 public static Double dateToSeconds(final Date date) {
118 if (date != null) {
119 return toSeconds(LocalTime.fromDateFields(date));
120 }
121 return null;
122 }
123 }