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