DateUtils { public static Date stringToDateWithFormat(String stringToConvert, String dateFormat) { if (stringToConvert != null) { try { DateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); Date date = simpleDateFormat.parse(stringToConvert); return date; } catch (ParseException e) { } } return new Date(0); } private  DateUtils(); static Date stringToDateWithFormat(String stringToConvert, String dateFormat); static String dateToStringWithFormat(Date dateToString, String dateFormat);  }
@Test public void testStringToDateWithFormatGoodDate() throws Exception { String stringDate = "2013-09-29T18:46:19Z"; Date date = DateUtils.stringToDateWithFormat(stringDate, DateFormatConstants.DATE_FORMAT_TIME); Date expectedDate = getCalendar(2013, Calendar.SEPTEMBER, 29, 18, 46, 19); assertThat(expectedDate, isDateEqualTo(date)); }
@Test public void testStringToDateWithFormatNotEquals() throws Exception { String stringDate = "2013-09-29T18:46:19Z"; Date date = DateUtils.stringToDateWithFormat(stringDate, DateFormatConstants.DATE_FORMAT_TIME); Date expectedDate = getCalendar(2000, Calendar.FEBRUARY, 10, 12, 12, 12); assertThat(expectedDate, not(isDateEqualTo(date))); }
@Test public void testStringToDateWithFormatWrongDate() throws Exception { String stringDate = "Valor Fake"; Date date = DateUtils.stringToDateWithFormat(stringDate, DateFormatConstants.DATE_FORMAT_TIME); Date expectedDate = new Date(0); assertThat(expectedDate, isDateEqualTo(date)); }
@Test public void testStringToDateWithFormatNullDate() throws Exception { Date date = DateUtils.stringToDateWithFormat(null, DateFormatConstants.DATE_FORMAT_TIME); assertNotNull(date); }
@Test public void testStringToDateWithFormatNoTimeGoodDate() throws Exception { String stringDate = "2013-09-29"; Date date = DateUtils.stringToDateWithFormat(stringDate, DateFormatConstants.DATE_FORMAT_NO_TIME); Date expectedDate = getCalendar(2013, Calendar.SEPTEMBER, 29, 0, 0, 0); assertThat(expectedDate, isDateEqualTo(date)); }