Skip to content

Instantly share code, notes, and snippets.

@markus2610
Forked from leviwilson/GsonDateFormatTest.java
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save markus2610/8918b2c010592a2a2cc1 to your computer and use it in GitHub Desktop.

Select an option

Save markus2610/8918b2c010592a2a2cc1 to your computer and use it in GitHub Desktop.
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