1 /*
2  * @(#) $Id: ASN1UTCTime.java,v 1.3 2003/07/08 08:13:52 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10package org.jstk.asn1;
11
12import java.io.ByteArrayOutputStream;
13
14
15public class ASN1UTCTime extends ASN1Type {
16    byte[] bytes = { 0x39, 0x31, 0x30, 0x35, 0x30, 0x36, 0x32, 0x33, 0x34,
17                  0x35, 0x34, 0x30, 0x5a };
18    public ASN1UTCTime(){
19        super(UNIVERSAL, NONE, UTCTime, UTCTime);
20    }
21
22    public java.util.Date getDate(){
23        java.text.SimpleDateFormat sdf = null;
24        if (value.length == 11 || value.length == 15)
25            sdf = new java.text.SimpleDateFormat("yyMMddHHmmZ");
26        else
27            sdf = new java.text.SimpleDateFormat("yyMMddHHmmssZ");
28        String text = new String(value);
29        text = text.replaceAll("Z", "+0000");
30        java.util.Date date = sdf.parse(text, new java.text.ParsePosition(0));
31
32        return date;
33    }
34    public void setDate(java.util.Date date){
35        StringBuffer sb = new StringBuffer();
36        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyMMddHHmmZ");
37        sdf.format(date, sb, new java.text.FieldPosition(0));
38        String dt = sb.toString().substring(0, 10) + "Z";
39        setValue(dt.getBytes());
40    }
41
42    public String toString(){
43        if (value == null)
44            return "ASN1UTCTime: null";
45        return "ASN1UTCTime: " + new String(value);
46    }
47
48    public static void main(String[] args){
49        byte[] bytes1 = { 0x39, 0x31, 0x30, 0x35, 0x30, 0x36, 0x32, 0x33, 0x34,
50                          0x35, 0x34, 0x30, 0x5a };
51        ASN1UTCTime ut1 = new ASN1UTCTime();
52        ut1.setValue(bytes1);
53        System.out.println(ut1.toString());
54        System.out.println(ut1.getDate().toString());
55
56
57        byte[] bytes2 = { 0x39, 0x31, 0x30, 0x35, 0x30, 0x36, 0x32, 0x33, 0x34,
58                          0x35, 0x34, 0x30, 0x2d, 0x30, 0x37, 0x30, 0x30 };
59        ASN1UTCTime ut2 = new ASN1UTCTime();
60        ut2.setValue(bytes2);
61        System.out.println(ut2.toString());
62        System.out.println(ut2.getDate().toString());
63    }
64}