日付処理
Java日付処理まとめ
・java.util.Date
・java.util.Calendar
・java.text.DateFormat / java.text.SimpleDateFormat
・java.sql.Date
java.util.Date date = new java.util.Date(); OK
java.sql.Date date = new java.sql.Date(); NG
java.util.Date date = new java.util.Date(long date); OK
java.sql.Date date = new java.sql.Date(long date); OK
Calendar today = Calendar.getInstance();
int year = today.get(Calendar.YEAR);
int month = today.get(Calendar.MONTH) + 1;
int date = today.get(Calendar.DATE);
HOUR
MINUTE
SECOND
MILLISECOND
HOUR_OF_DAY 時刻
DAY_OF_YEAR 現在の年の何日目
DAY_OF_WEEK 曜日
DAY_OF_WEEK_IN_MONTH 現在の月の何度目
today.set(Calendar.YEAR, 2013);
today.set(Calendar.MONTH, 1);
today.set(Calendar.DATE, today.getActualMaximum(Calendar.DATE));
today.add(Calendar.DATE, 3);
today.add(Calendar.DATE, -5);
※getActualMaximum:月の末日を取得
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // 曜日:EEEE
SimpleDateFormat(String pattern, [Locale locale])
String out = dateFormat.format(new java.util.Date(today.getTimeInMillis()));
y, M, d(月における日), H(0~23), h(0~11), m, s, S(ミリ秒)
D(年における日), E(曜日), F(月における曜日)
★型変換
// string ⇒ Date
java.util.Date date =
java.text.DateFormat.getDateInstance().parse("2013-01-30");
或いは
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2013-01-30"); // ParseException
// string ⇒ Timestamp
str = str.replace("/", "-");
Timestamp result = Timestamp.valueOf(str); // IllegalArgumentException
// util.Date ⇒ sql.Date
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
★フォーマット
public static String toString(Date d) {
// 方法1
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
return sdf.format(d);
// 方法2
String format = “%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS”;
return String.format(format, d);
}
★日数差を求める
方法1
Calendar today = Calendar.getInstance();
Calendar todayNextYear = Calendar.getInstance().add(Calendar.YEAR, 1);
long diffTime = todayNextYear.getTimeInMillis() - today.getTimeInMillis();
long diffDay = diffTime / 1000 / 60 / 60 / 24;
方法2
Date date1;
Date date2;
//ミリ秒単位で差を求める
long result = date1.getTime() - date2.getTime();
//日数に換算する
result = result / ( 24 * 60 * 60 * 1000 );
★ファイルの最終更新日の取得
File file = new File("C:\test.txt");
long lastMod = file.lastModified();
// 戻り値はグリニッジ標準時(1970年1月1日0時0分0秒) からミリ秒単位
★月の最大日付の取得
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int maxDate = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
★現在システム時間の取得
// 方法1
Timestamp time = new Timestamp(System.currentTimeMillis());
// 方法2
Date date = new Date();
Timestamp time = new Timestamp(date.getTime());
★消費時間の計算
long t1 = System.currentTimeMillis();
// do something
long t2 = System.currentTimeMillis() ;
long time = t2 - t1;
★JavaのSimpleDateFormatの注意点
スレッドセーフではないクラス
private static final SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String formatDate(Date date) throws ParseException{
return sdf.format(date);
}
public static Date parse(String strDate) throws ParseException{
return sdf.parse(strDate);
}
対策1 毎回オブジェクト生成
public static String formatDate(Date date) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
対策2 Synchronizedで同期
public static String formatDate(Date date) throws ParseException{
synchronized(sdf){
return sdf.format(date);
}
}
対策3 ThreadLocalクラスの利用
private static ThreadLocal<DateFormat> threadLocal
= new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static String format(Date date) throws ParseException {
return threadLocal.get().format(date);
}
対策4 JDK以外のライブラリ
Apache CommonsのFastDateFormatクラス
import org.apache.commons.lang.time.FastDateFormat;
private static final Format fdf
= FastDateFormat.getInstance("yyyy-MM-dd");
或いは
= DateFormatUtils.ISO_DATE_FORMAT; // 定義済みyyyy-MM-dd
public static String formatDate(Date date) throws ParseException{
return fdf.format(date);
}
※日付の文字列は×
Joda Time
public static String formatDate(Date date) throws ParseException{
DateTime dateTime = new DateTime(new Date().getTime());
return dateTime.toString("yyyy-MM-dd HH:mm:ss");
}
public static Date parse(String strDate) throws ParseException{
DateTime dateTime = new DateTime(strDate);
return new Date(dateTime.getMillis());
}
※速度:
対策1 < 対策2 < 対策3 ≒ 対策4
★Calculate Age from Birthday
Jodatime
LocalDate birthday = new LocalDate(1990, 1, 23);
LocalDate today = new LocalDate();
Period period = new Period(birthday, today, PeriodType.yearMonthDay());
period.getDays();
period.getMonths();
period.getYears();
Java 8
LocalDate birthday = LocalDate.of(1990, Month.JANUARY, 23);
LocalDate today = LocalDate.now();
Period period = Period.between(birthday, today);
period.getDays();
period.getMonths();
period.getYears();