2 * Copyright 2011 BitMeister Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package jp.bitmeister.asn1.type;
18 import java.nio.charset.Charset;
19 import java.text.DateFormat;
20 import java.util.Calendar;
21 import java.util.Date;
22 import java.util.regex.Pattern;
24 import jp.bitmeister.asn1.processor.ASN1Visitor;
27 * The base class for types which contains a {@code String} that represents date
31 * This class provides generic interfaces and common methods for classes which
32 * represents date and time types.
35 * @author WATANABE, Jun. <jwat at bitmeister.jp>
37 public abstract class TimeType extends StringType {
39 private static final Pattern pattern = Pattern.compile("[0-9\\.Z\\+\\-]*");
42 * Converts the {@code Date} object to a formatted {@code String} that
43 * represents date and time, and set it to this instance.
46 * The {@code Date} to be assigned.
48 public void set(Date value) {
49 set(form().format(value));
53 * Returns a {@code Date} converted from the value of this instance.
55 * @return A {@code Date}.
60 String value = stringValue();
61 if (value.endsWith("Z")) {
62 // represents UTC time.
63 differential = "+0000";
64 time = value.substring(0, value.length() - 1);
65 } else if (value.indexOf("+") < 0 && value.indexOf("-") < 0) {
66 // represents the local time
67 differential = String.format("%tz", Calendar.getInstance());
70 // represents the local time, and the time differential
71 differential = value.substring(value.length() - 5, value.length());
72 time = value.substring(0, value.length() - 5);
74 return parseDate(time, differential);
78 * Returns the {@code DateFormat} used for formatting the date and time.
80 * @return The date format.
82 public abstract DateFormat form();
85 public Charset charset() {
86 return Charset.forName("US-ASCII");
92 * @see jp.bitmeister.asn1.type.StringType#pattern()
95 protected Pattern pattern() {
103 * jp.bitmeister.asn1.type.StringType#accept(jp.bitmeister.asn1.processor
107 public <E extends Throwable> void accept(ASN1Visitor<E> visitor) throws E {
112 * Parses and converts the strings represents a set of date, time and time
113 * defferential to a {@code Date}.
116 * The {@code String} represents a set of date.
117 * @param differential
118 * The {@code String} represents a time differential.
119 * @return A {@code Date} object that converted from the time and the
122 protected abstract Date parseDate(String time, String differential);