1 package org.bouncycastle.asn1.x509;
2
3 import java.util.Date;
4 import java.util.SimpleTimeZone;
5 import java.text.ParsePosition;
6 import java.text.SimpleDateFormat;
7
8 import org.bouncycastle.asn1.*;
9
10 public class Time
11 implements DEREncodable
12 {
13 DERObject time;
14
15 public static Time getInstance(
16 ASN1TaggedObject obj,
17 boolean explicit)
18 {
19 return getInstance(obj.getObject());
20 }
21
22 public Time(
23 DERObject time)
24 {
25 if (!(time instanceof DERUTCTime)
26 && !(time instanceof DERGeneralizedTime))
27 {
28 throw new IllegalArgumentException("unknown object passed to Time");
29 }
30
31 this.time = time;
32 }
33
34
39 public Time(
40 Date date)
41 {
42 SimpleTimeZone tz = new SimpleTimeZone(0, "Z");
43 SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss");
44
45 dateF.setTimeZone(tz);
46
47 String d = dateF.format(date) + "Z";
48 int year = Integer.parseInt(d.substring(0, 4));
49
50 if (year < 1950 || year > 2049)
51 {
52 time = new DERGeneralizedTime(d);
53 }
54 else
55 {
56 time = new DERUTCTime(d.substring(2));
57 }
58 }
59
60 public static Time getInstance(
61 Object obj)
62 {
63 if (obj instanceof Time)
64 {
65 return (Time)obj;
66 }
67 else if (obj instanceof DERUTCTime)
68 {
69 return new Time((DERUTCTime)obj);
70 }
71 else if (obj instanceof DERGeneralizedTime)
72 {
73 return new Time((DERGeneralizedTime)obj);
74 }
75
76 throw new IllegalArgumentException("unknown object in factory");
77 }
78
79 public String getTime()
80 {
81 if (time instanceof DERUTCTime)
82 {
83 return ((DERUTCTime)time).getAdjustedTime();
84 }
85 else
86 {
87 return ((DERGeneralizedTime)time).getTime();
88 }
89 }
90
91 public Date getDate()
92 {
93 SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
94
95 return dateF.parse(this.getTime(), new ParsePosition(0));
96 }
97
98
105 public DERObject getDERObject()
106 {
107 return time;
108 }
109 }
110