1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.openehealth.ipf.commons.core.datetime;
17
18 import java.util.Date;
19 import java.util.regex.Pattern;
20
21
22
23
24 public class Duration {
25
26 private static final String EMPTY = "";
27 private static final Pattern PATTERN = Pattern.compile("^[0-9]+[smhd]?$");
28 private static final Pattern PATTERN_UNIT = Pattern.compile("[smhd]");
29 private static final Pattern PATTERN_NUMBER = Pattern.compile("[0-9]+");
30
31 private static final String SECOND = "s";
32 private static final String MINUTE = "m";
33 private static final String HOUR = "h";
34 private static final String DAY = "d";
35
36
37 private final long milliseconds;
38
39 public Duration(long milliseconds) {
40 this.milliseconds = milliseconds;
41 }
42
43 public long getValue() {
44 return milliseconds;
45 }
46
47 public Date since() {
48 return since(new Date());
49 }
50
51 public Date since(Date date) {
52 return new Date(date.getTime() - milliseconds);
53 }
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73 public static Duration parse(String duration) {
74 String d = duration.trim();
75 if (!PATTERN.matcher(d).matches()) {
76 throw new DurationFormatException(
77 "Duration string " + duration + " doesn't match pattern " + PATTERN);
78 }
79 String u = PATTERN_NUMBER.matcher(d).replaceFirst(EMPTY);
80 long v = Long.parseLong(PATTERN_UNIT.matcher(d).replaceFirst(EMPTY));
81 if (u.length() == 0) {
82
83 } else if (u.equals(SECOND)) {
84 v = v * 1000L;
85 } else if (u.equals(MINUTE)) {
86 v = v * 1000L * 60L;
87 } else if (u.equals(HOUR)) {
88 v = v * 1000L * 60L * 60L;
89 } else if (u.equals(DAY)) {
90 v = v * 1000L * 60L * 60L * 24L;
91 }
92 return new Duration(v);
93 }
94
95 }