Iso8601Utils { static String format(Date date) { Calendar calendar = new GregorianCalendar(TIMEZONE_Z, Locale.US); calendar.setTime(date); int capacity = "yyyy-MM-ddThh:mm:ss.sssZ".length(); StringBuilder formatted = new StringBuilder(capacity); padInt(formatted, calendar.get(Calendar.YEAR), "yyyy".length()); formatted.append('-'); padInt(formatted, calendar.get(Calendar.MONTH) + 1, "MM".length()); formatted.append('-'); padInt(formatted, calendar.get(Calendar.DAY_OF_MONTH), "dd".length()); formatted.append('T'); padInt(formatted, calendar.get(Calendar.HOUR_OF_DAY), "hh".length()); formatted.append(':'); padInt(formatted, calendar.get(Calendar.MINUTE), "mm".length()); formatted.append(':'); padInt(formatted, calendar.get(Calendar.SECOND), "ss".length()); formatted.append('.'); padInt(formatted, calendar.get(Calendar.MILLISECOND), "sss".length()); formatted.append('Z'); return formatted.toString(); }    }
@Test public void toJson() throws Exception { assertThat(format(newDate(1970, 1, 1, 0, 0, 0, 0, 0))).isEqualTo("1970-01-01T00:00:00.000Z"); assertThat(format(newDate(1985, 4, 12, 23, 20, 50, 520, 0))) .isEqualTo("1985-04-12T23:20:50.520Z"); assertThat(format(newDate(1996, 12, 19, 16, 39, 57, 0, -8 * 60))) .isEqualTo("1996-12-20T00:39:57.000Z"); assertThat(format(newDate(1990, 12, 31, 23, 59, 59, 0, 0))) .isEqualTo("1990-12-31T23:59:59.000Z"); assertThat(format(newDate(1990, 12, 31, 15, 59, 59, 0, -8 * 60))) .isEqualTo("1990-12-31T23:59:59.000Z"); assertThat(format(newDate(1937, 1, 1, 12, 0, 27, 870, 20))) .isEqualTo("1937-01-01T11:40:27.870Z"); }