01: /*
02: * Copyright (C) 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 03. October 2005 by Joerg Schaible
11: */
12: package com.thoughtworks.xstream.converters.extended;
13:
14: import java.sql.Timestamp;
15: import java.util.Date;
16:
17: /**
18: * A SqlTimestampConverter conforming to the ISO8601 standard.
19: * http://www.iso.ch/iso/en/CatalogueDetailPage.CatalogueDetail?CSNUMBER=26780
20: *
21: * @author Jörg Schaible
22: * @since 1.1.3
23: */
24: public class ISO8601SqlTimestampConverter extends ISO8601DateConverter {
25:
26: private final static String PADDING = "000000000";
27:
28: public boolean canConvert(Class type) {
29: return type.equals(Timestamp.class);
30: }
31:
32: public Object fromString(String str) {
33: final int idxFraction = str.lastIndexOf('.');
34: int nanos = 0;
35: if (idxFraction > 0) {
36: int idx;
37: for (idx = idxFraction + 1; Character.isDigit(str
38: .charAt(idx)); ++idx)
39: ;
40: nanos = Integer.parseInt(str
41: .substring(idxFraction + 1, idx));
42: str = str.substring(0, idxFraction) + str.substring(idx);
43: }
44: final Date date = (Date) super .fromString(str);
45: final Timestamp timestamp = new Timestamp(date.getTime());
46: timestamp.setNanos(nanos);
47: return timestamp;
48: }
49:
50: public String toString(Object obj) {
51: final Timestamp timestamp = (Timestamp) obj;
52: String str = super .toString(new Date(
53: (timestamp.getTime() / 1000) * 1000));
54: final String nanos = String.valueOf(timestamp.getNanos());
55: final int idxFraction = str.lastIndexOf('.');
56: str = str.substring(0, idxFraction + 1)
57: + PADDING.substring(nanos.length()) + nanos
58: + str.substring(idxFraction + 4);
59: return str;
60: }
61:
62: }
|