Skip to content

Instantly share code, notes, and snippets.

@leviwilson
Created April 26, 2012 03:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leviwilson/2495636 to your computer and use it in GitHub Desktop.
Save leviwilson/2495636 to your computer and use it in GitHub Desktop.
Gson Date / Milliseconds
package com.leviwilson.test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import java.util.Date;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonDateFormatTest {
@Test
public void itFailsToGoBackAndForthByDefault() {
Date now = new Date();
Gson defaultGson = new Gson();
final String jsonDate = defaultGson.toJson(now, Date.class);
// This is the problem that you were seeing before
assertThat(defaultGson.fromJson(jsonDate, Date.class), is(not(now)));
}
@Test
public void itSucceedsWhenIncludingMillisecondsByDefault() {
Date now = new Date();
// I think this would fix the issue
Gson gsonWithDateFormat = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.create();
final String jsonDate = gsonWithDateFormat.toJson(now, Date.class);
assertThat(gsonWithDateFormat.fromJson(jsonDate, Date.class), is(now));
}
@Test
public void itUsesDefaultsForDateAndTime() {
Date now = new Date();
Gson defaultGson = new Gson();
Gson builderGson = new GsonBuilder()
.setDateFormat(DateFormat.DEFAULT, DateFormat.DEFAULT)
.create();
assertThat(builderGson.toJson(now, Date.class), is(defaultGson.toJson(now, Date.class)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment