1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jadira.bindings.core.jdk;
17
18 import java.text.ParseException;
19 import java.text.SimpleDateFormat;
20 import java.util.Date;
21 import java.util.TimeZone;
22
23 import org.jadira.bindings.core.api.Binding;
24
25
26
27
28
29 public class DateStringBinding extends AbstractStringBinding<Date> implements Binding<Date, String> {
30
31 private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
32 @Override
33 public SimpleDateFormat initialValue() {
34 final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
35 formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
36 return formatter;
37 }
38 };
39
40
41
42
43 @Override
44 public Date unmarshal(String object) {
45
46 if (object.length() != 29) {
47 throw new IllegalArgumentException("Invalid date: " + object);
48 }
49 final String result = object.substring(0, 26) + object.substring(27);
50
51 try {
52 return DATE_FORMAT.get().parse(result);
53 } catch (ParseException ex) {
54 throw new IllegalArgumentException("Invalid date: " + object);
55 }
56 }
57
58
59
60
61 @Override
62 public String marshal(Date object) {
63
64 String output = DATE_FORMAT.get().format(object);
65 return output.substring(0, 26) + ":" + output.substring(26);
66 }
67
68
69
70
71
72 public Class<Date> getBoundClass() {
73 return Date.class;
74 }
75 }