1
16
17 package com.google.gson.internal.bind;
18
19 import com.google.gson.Gson;
20 import com.google.gson.JsonSyntaxException;
21 import com.google.gson.TypeAdapter;
22 import com.google.gson.TypeAdapterFactory;
23 import com.google.gson.internal.JavaVersion;
24 import com.google.gson.internal.PreJava9DateFormatProvider;
25 import com.google.gson.internal.bind.util.ISO8601Utils;
26 import com.google.gson.reflect.TypeToken;
27 import com.google.gson.stream.JsonReader;
28 import com.google.gson.stream.JsonToken;
29 import com.google.gson.stream.JsonWriter;
30
31 import java.io.IOException;
32 import java.text.DateFormat;
33 import java.text.ParseException;
34 import java.text.ParsePosition;
35 import java.util.ArrayList;
36 import java.util.Date;
37 import java.util.List;
38 import java.util.Locale;
39
40
46 public final class DateTypeAdapter extends TypeAdapter<Date> {
47 public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
48 @SuppressWarnings("unchecked")
49 @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
50 return typeToken.getRawType() == Date.class ? (TypeAdapter<T>) new DateTypeAdapter() : null;
51 }
52 };
53
54
58 private final List<DateFormat> dateFormats = new ArrayList<DateFormat>();
59
60 public DateTypeAdapter() {
61 dateFormats.add(DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US));
62 if (!Locale.getDefault().equals(Locale.US)) {
63 dateFormats.add(DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT));
64 }
65 if (JavaVersion.isJava9OrLater()) {
66 dateFormats.add(PreJava9DateFormatProvider.getUSDateTimeFormat(DateFormat.DEFAULT, DateFormat.DEFAULT));
67 }
68 }
69
70 @Override public Date read(JsonReader in) throws IOException {
71 if (in.peek() == JsonToken.NULL) {
72 in.nextNull();
73 return null;
74 }
75 return deserializeToDate(in.nextString());
76 }
77
78 private synchronized Date deserializeToDate(String json) {
79 for (DateFormat dateFormat : dateFormats) {
80 try {
81 return dateFormat.parse(json);
82 } catch (ParseException ignored) {}
83 }
84 try {
85 return ISO8601Utils.parse(json, new ParsePosition(0));
86 } catch (ParseException e) {
87 throw new JsonSyntaxException(json, e);
88 }
89 }
90
91 @Override public synchronized void write(JsonWriter out, Date value) throws IOException {
92 if (value == null) {
93 out.nullValue();
94 return;
95 }
96 String dateFormatAsString = dateFormats.get(0).format(value);
97 out.value(dateFormatAsString);
98 }
99
100
101 }
102