01: // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
02:
03: package org.xbill.DNS;
04:
05: /**
06: * Routines for converting time values to and from YYYYMMDDHHMMSS format.
07: *
08: * @author Brian Wellington
09: */
10:
11: import java.util.*;
12: import java.text.*;
13:
14: final class FormattedTime {
15:
16: private static NumberFormat w2, w4;
17:
18: static {
19: w2 = new DecimalFormat();
20: w2.setMinimumIntegerDigits(2);
21:
22: w4 = new DecimalFormat();
23: w4.setMinimumIntegerDigits(4);
24: w4.setGroupingUsed(false);
25: }
26:
27: private FormattedTime() {
28: }
29:
30: /**
31: * Converts a Date into a formatted string.
32: * @param date The Date to convert.
33: * @return The formatted string.
34: */
35: public static String format(Date date) {
36: Calendar c = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
37: StringBuffer sb = new StringBuffer();
38:
39: c.setTime(date);
40: sb.append(w4.format(c.get(Calendar.YEAR)));
41: sb.append(w2.format(c.get(Calendar.MONTH) + 1));
42: sb.append(w2.format(c.get(Calendar.DAY_OF_MONTH)));
43: sb.append(w2.format(c.get(Calendar.HOUR_OF_DAY)));
44: sb.append(w2.format(c.get(Calendar.MINUTE)));
45: sb.append(w2.format(c.get(Calendar.SECOND)));
46: return sb.toString();
47: }
48:
49: /**
50: * Parses a formatted time string into a Date.
51: * @param s The string, in the form YYYYMMDDHHMMSS.
52: * @return The Date object.
53: * @throws TextParseExcetption The string was invalid.
54: */
55: public static Date parse(String s) throws TextParseException {
56: Calendar c = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
57:
58: if (s.length() != 14) {
59: throw new TextParseException("Invalid time encoding: " + s);
60: }
61: try {
62: int year = Integer.parseInt(s.substring(0, 4));
63: int month = Integer.parseInt(s.substring(4, 6)) - 1;
64: int date = Integer.parseInt(s.substring(6, 8));
65: int hour = Integer.parseInt(s.substring(8, 10));
66: int minute = Integer.parseInt(s.substring(10, 12));
67: int second = Integer.parseInt(s.substring(12, 14));
68: c.set(year, month, date, hour, minute, second);
69: } catch (NumberFormatException e) {
70: throw new TextParseException("Invalid time encoding: " + s);
71: }
72: return c.getTime();
73: }
74:
75: }
|