Created
April 26, 2012 03:47
-
-
Save leviwilson/2495636 to your computer and use it in GitHub Desktop.
Gson Date / Milliseconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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