5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【JUnit】Date型の使い方

Last updated at Posted at 2016-03-14
  • Date型の使い方
  • Calendarはなるべく使わない、可読性の損なわないJUnitの書き方を探る
  • SimpleDateFormatもなるべく使わない

String("yyyy-MM-dd")をsql.Date型に変換

code
// java.sql.Date.valueOf(String s) を使用
// 時刻は00:00:00.000
java.sql.Date.valueOf("2099-01-01"); // 2099-01-01

String("yyyy-MM-dd")をutil.Date型に変換

code
import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.format.DateTimeFormat;
import org.apache.commons.lang3.time.FastDateFormat;
// Thu Jan 01 00:00:00 JST 2099
// ■case1:DateUtils.parseDate(date, pattern) を使用
DateUtils.parseDate("2099-01-01", "yyyy-MM-dd");
/*
■case2:DateTimeFormat.parseDateTime(date).toDate()を使用
Exceptionが出ないのが良い
*/
DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime("2037-12-31").toDate();
// 時刻指定も可 Thu Jan 01 10:10:10 JST 2099
DateUtils.parseDate("2099-01-01 10:10:10", "yyyy-MM-dd HH:mm:ss");
// ■case3:FastDateFormat.parse(date)を使用
FastDateFormat.getInstance("yyyy-MM-dd").parse("2037-12-31");

Date型(util.Date、sql.Date)をStringに変換

code
// ■case1:DateFormatUtils.format(date, pattern) を使用
import org.apache.commons.lang3.time.DateFormatUtils;
DateFormatUtils.format(date, "yyyy/MM/dd hh:mm:ss"); // 2099/01/01 00:00:00
// ■case2:FastDateFormat.format(string)を使用
FastDateFormat.getInstance("yyyy-MM-dd").format(date);

その他、util.Date型に変換

code
// DateTimeコンストラクタからDate生成
// Fri Jan 02 03:04:05 JST 2099
new DateTime(2099, 1, 2, 3, 4, 5).toDate();

JUnitの評価

JUnitcode
// 時間は無視して、同日か比較
assertTrue(DateUtils.isSameDay(actual.getDate(), DateUtils.parseDate("2099-01-01", "yyyy-MM-dd")));
// 完全一致を比較
assertThat(actual.getDate(), is(DateUtils.parseDate("2099-01-01 10:10:10", "yyyy-MM-dd hh:mm:ss")));
5
7
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?