1 package org.opentrafficsim.core.network.factory.xml.units;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import org.djunits.unit.TimeUnit;
7 import org.djunits.value.vdouble.scalar.Time;
8 import org.opentrafficsim.core.network.NetworkException;
9
10
11
12
13
14
15
16
17
18
19
20 public final class TimeUnits
21 {
22
23 public static final Map<String, TimeUnit> TIME_UNITS = new HashMap<>();
24
25 static
26 {
27 TIME_UNITS.put("ms", TimeUnit.EPOCH_MILLISECOND);
28 TIME_UNITS.put("s", TimeUnit.EPOCH_SECOND);
29 TIME_UNITS.put("m", TimeUnit.EPOCH_MINUTE);
30 TIME_UNITS.put("min", TimeUnit.EPOCH_MINUTE);
31 TIME_UNITS.put("h", TimeUnit.EPOCH_HOUR);
32 TIME_UNITS.put("hr", TimeUnit.EPOCH_HOUR);
33 TIME_UNITS.put("d", TimeUnit.EPOCH_DAY);
34 TIME_UNITS.put("day", TimeUnit.EPOCH_DAY);
35 TIME_UNITS.put("wk", TimeUnit.EPOCH_WEEK);
36 TIME_UNITS.put("week", TimeUnit.EPOCH_WEEK);
37 }
38
39
40 private TimeUnits()
41 {
42
43 }
44
45
46
47
48
49
50 public static String parseTimeUnit(final String s) throws NetworkException
51 {
52 String u = null;
53 for (String us : TIME_UNITS.keySet())
54 {
55 if (s.toString().contains(us))
56 {
57 if (u == null || us.length() > u.length())
58 {
59 u = us;
60 }
61 }
62 }
63 if (u == null)
64 {
65 throw new NetworkException("Parsing network: cannot instantiate time unit in: " + s);
66 }
67 return u;
68 }
69
70
71
72
73
74
75 public static Time parseTime(final String s) throws NetworkException
76 {
77 String us = parseTimeUnit(s);
78 TimeUnit u = TIME_UNITS.get(us);
79 String sv = s.substring(0, s.indexOf(us));
80 try
81 {
82 double value = Double.parseDouble(sv);
83 return new Time(value, u);
84 }
85 catch (NumberFormatException nfe)
86 {
87 throw new NetworkException("Parsing network: cannot instantiate scalar: " + s, nfe);
88 }
89 }
90
91 }