Skip to content

Instantly share code, notes, and snippets.

@froop
Created January 12, 2012 06:08
Show Gist options
  • Select an option

  • Save froop/1599046 to your computer and use it in GitHub Desktop.

Select an option

Save froop/1599046 to your computer and use it in GitHub Desktop.
[Java] 日付文字列をDate型へ変換
public static Date toDate(String value) throws ParseException {
final String[] formats = {"yyyyMMdd", "yyyy/MM/dd", "yyyy-MM-dd"};
ParseException parseEx = null;
for (String format : formats) {
try {
return toDate(value, format);
} catch (ParseException e) {
parseEx = e;
continue;
}
}
throw parseEx;
}
private static Date toDate(String value, String format)
throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
return formatter.parse(value);
}
@Test
public void testToDateYYYYMMDD() throws ParseException {
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("20110102").toString());
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("20110102a").toString());
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("2011012").toString());
}
@Test
public void testToDateSlash() throws ParseException {
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("2011/01/02").toString());
}
@Test
public void testToDateSlashNonZero() throws ParseException {
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("2011/1/2").toString());
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("2011/1/2a").toString());
}
@Test
public void testToDateHyphen() throws ParseException {
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("2011-01-02").toString());
}
@Test
public void testToDateHyphenNonZero() throws ParseException {
assertEquals("Sun Jan 02 00:00:00 JST 2011", toDate("2011-1-2").toString());
}
@Test(expected=ParseException.class)
public void testToDateErrorChar() throws ParseException {
toDate("abcd/ef/gh");
}
@Test(expected=ParseException.class)
public void testToDateErrorNotExists() throws ParseException {
toDate("20110431");
}
@Test(expected=ParseException.class)
public void testToDateErrorLength() throws ParseException {
toDate("201108310");
}
@Test(expected=ParseException.class)
public void testToDateErrorLengthDay() throws ParseException {
toDate("2011/08/310");
}
@Test(expected=ParseException.class)
public void testToDateErrorLengthMonth() throws ParseException {
toDate("2011-080-31");
}
@Test(expected=ParseException.class)
public void testToDateErrorNotDate() throws ParseException {
toDate("20110100");
}
@Test
public void testToDateLeapYear() throws ParseException {
assertEquals("Wed Feb 29 00:00:00 JST 2012", toDate("20120229").toString());
}
@Test(expected=ParseException.class)
public void testToDateErrorNotLeapYear() throws ParseException {
toDate("20110229");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment