summaryrefslogtreecommitdiff
path: root/src/utils
diff options
context:
space:
mode:
authorPeter Wu <peter@lekensteyn.nl>2014-05-10 18:29:17 +0200
committerPeter Wu <peter@lekensteyn.nl>2014-05-10 18:29:17 +0200
commit6721eeaf2367bc852446ba9b431a8464daa56ad1 (patch)
treee116aa0039226650e2e28865b3e35d2cc508d004 /src/utils
parentbb7e2b32ef5ef531ac3f007c09206c4a9db32ca9 (diff)
downloadDatafiller-6721eeaf2367bc852446ba9b431a8464daa56ad1.tar.gz
Convert String to DateTime (for created_at)
Extra efforts are done to keep the timezone information.
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/TwitterDateAdapter.java51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/utils/TwitterDateAdapter.java b/src/utils/TwitterDateAdapter.java
new file mode 100644
index 0000000..b3c8f37
--- /dev/null
+++ b/src/utils/TwitterDateAdapter.java
@@ -0,0 +1,51 @@
+package utils;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+import java.lang.reflect.Type;
+import org.joda.time.DateTime;
+import org.joda.time.format.DateTimeFormat;
+import org.joda.time.format.DateTimeFormatter;
+
+/**
+ * Converts a Twitter date string to a DateTime with timezone.
+ *
+ * @author Peter Wu
+ */
+public class TwitterDateAdapter implements JsonDeserializer<DateTime>,
+ JsonSerializer<DateTime> {
+
+ private static final DateTimeFormatter DATE_FORMATTER
+ = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy")
+ .withOffsetParsed();
+
+ @Override
+ public DateTime deserialize(JsonElement je, Type type,
+ JsonDeserializationContext jdc) throws JsonParseException {
+ JsonPrimitive jp;
+ if (!je.isJsonPrimitive() || !(jp = je.getAsJsonPrimitive()).isString()) {
+ throw new JsonParseException("Invalid date type");
+ }
+ String datetime = jp.getAsString();
+ try {
+ return DATE_FORMATTER.parseDateTime(datetime);
+ } catch (IllegalArgumentException ex) {
+ throw new JsonParseException("Invalid date: " + datetime, ex);
+ }
+ }
+
+ @Override
+ public JsonElement serialize(DateTime t, Type type,
+ JsonSerializationContext jsc) {
+ return new JsonPrimitive(formatDateTime(t));
+ }
+
+ public static String formatDateTime(DateTime t) {
+ return DATE_FORMATTER.print(t);
+ }
+}