source: josm/trunk/src/org/openstreetmap/josm/data/gpx/GpxTimezone.java@ 15847

Last change on this file since 15847 was 15847, checked in by simon04, 4 years ago

Fix typo in Javadoc

  • Property svn:eol-style set to native
File size: 2.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.gpx;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.text.ParseException;
7import java.util.Objects;
8import java.util.regex.Matcher;
9import java.util.regex.Pattern;
10
11/**
12 * Timezone in hours.<p>
13 * TODO: should probably be replaced by {@link java.util.TimeZone}.
14 * @since 14205 (extracted from {@code CorrelateGpxWithImages})
15 */
16public final class GpxTimezone {
17
18 /**
19 * The timezone 0.
20 */
21 public static final GpxTimezone ZERO = new GpxTimezone(0.0);
22 private final double timezone;
23
24 /**
25 * Constructs a new {@code GpxTimezone}.
26 * @param hours timezone in hours
27 */
28 public GpxTimezone(double hours) {
29 this.timezone = hours;
30 }
31
32 /**
33 * Returns the timezone in hours.
34 * @return the timezone in hours
35 */
36 public double getHours() {
37 return timezone;
38 }
39
40 /**
41 * Formats time zone.
42 * @return formatted time zone. Format: ±HH:MM
43 */
44 public String formatTimezone() {
45 StringBuilder ret = new StringBuilder();
46
47 double tz = this.timezone;
48 if (tz < 0) {
49 ret.append('-');
50 tz = -tz;
51 } else {
52 ret.append('+');
53 }
54 ret.append((long) tz).append(':');
55 int minutes = (int) ((tz % 1) * 60);
56 if (minutes < 10) {
57 ret.append('0');
58 }
59 ret.append(minutes);
60
61 return ret.toString();
62 }
63
64 /**
65 * Parses timezone.
66 * @param timezone timezone. Expected format: ±HH:MM
67 * @return timezone
68 * @throws ParseException if timezone can't be parsed
69 */
70 public static GpxTimezone parseTimezone(String timezone) throws ParseException {
71 if (timezone.isEmpty())
72 return ZERO;
73
74 Matcher m = Pattern.compile("^([\\+\\-]?)(\\d{1,2})(?:\\:([0-5]\\d))?$").matcher(timezone);
75
76 ParseException pe = new ParseException(tr("Error while parsing timezone.\nExpected format: {0}", "±HH:MM"), 0);
77 try {
78 if (m.find()) {
79 int sign = "-".equals(m.group(1)) ? -1 : 1;
80 int hour = Integer.parseInt(m.group(2));
81 int min = m.group(3) == null ? 0 : Integer.parseInt(m.group(3));
82 return new GpxTimezone(sign * (hour + min / 60.0));
83 }
84 } catch (IndexOutOfBoundsException | NumberFormatException ex) {
85 pe.initCause(ex);
86 }
87 throw pe;
88 }
89
90 @Override
91 public boolean equals(Object o) {
92 if (this == o) return true;
93 if (!(o instanceof GpxTimezone)) return false;
94 GpxTimezone timezone1 = (GpxTimezone) o;
95 return Double.compare(timezone1.timezone, timezone) == 0;
96 }
97
98 @Override
99 public int hashCode() {
100 return Objects.hash(timezone);
101 }
102}
Note: See TracBrowser for help on using the repository browser.