/src/test/java/com/alibaba/json/bvt/serializer/date/DateTest_ISO8601_TimeZone.java

https://github.com/alibaba/fastjson · Java · 76 lines · 54 code · 22 blank · 0 comment · 0 complexity · 4af407a9490d6826904eaf7e8c8466d8 MD5 · raw file

  1. package com.alibaba.json.bvt.serializer.date;
  2. import java.util.Calendar;
  3. import java.util.Date;
  4. import java.util.HashMap;
  5. import java.util.Locale;
  6. import java.util.Map;
  7. import java.util.TimeZone;
  8. import junit.framework.TestCase;
  9. import org.junit.Assert;
  10. import com.alibaba.fastjson.JSON;
  11. import com.alibaba.fastjson.TypeReference;
  12. import com.alibaba.fastjson.serializer.SerializerFeature;
  13. public class DateTest_ISO8601_TimeZone extends TestCase {
  14. protected void setUp() throws Exception {
  15. JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
  16. JSON.defaultLocale = Locale.CHINA;
  17. }
  18. public void test_date1() throws Exception {
  19. Map<String,Date> map = new HashMap<String,Date>();
  20. map.put("date", new Date(1425886057586l));
  21. String json = JSON.toJSONString(map, SerializerFeature.UseISO8601DateFormat);
  22. Assert.assertEquals("{\"date\":\"2015-03-09T15:27:37.586+08:00\"}", json);
  23. Map<String,Date> newMap = JSON.parseObject(json, new TypeReference<Map<String,Date>>(){});
  24. Assert.assertEquals(1425886057586l, newMap.get("date").getTime());
  25. }
  26. public void test_date2() throws Exception {
  27. Calendar c = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale);
  28. c.setTimeZone(TimeZone.getTimeZone("GMT+10"));
  29. VO v = new VO();
  30. v.setGmtCreate(c);
  31. String json = JSON.toJSONString(v, SerializerFeature.UseISO8601DateFormat);
  32. System.out.println(json);
  33. Calendar cal = JSON.parseObject(json, VO.class).getGmtCreate();
  34. Assert.assertEquals(10, cal.getTimeZone().getRawOffset() / (3600 * 1000));
  35. }
  36. public void test_date3() throws Exception {
  37. Calendar c = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale);
  38. VO v = new VO();
  39. v.setGmtCreate(c);
  40. String json = JSON.toJSONString(v, SerializerFeature.UseISO8601DateFormat);
  41. System.out.println(json);
  42. Calendar cal = JSON.parseObject(json, VO.class).getGmtCreate();
  43. Assert.assertEquals(8, cal.getTimeZone().getRawOffset() / (3600 * 1000));
  44. }
  45. public static class VO {
  46. private Calendar gmtCreate;
  47. public Calendar getGmtCreate() {
  48. return gmtCreate;
  49. }
  50. public void setGmtCreate(Calendar gmtCreate) {
  51. this.gmtCreate = gmtCreate;
  52. }
  53. }
  54. }