facebook twitter hatena line email

Java/日付

提供: 初心者エンジニアの簡易メモ
2018年11月8日 (木) 14:41時点におけるAdmin (トーク | 投稿記録)による版 (Calendarが推奨)

移動: 案内検索

日付比較

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date ddate = sdf.parse("2012-10-10 10:10");
Date today = new Date();
if (today.compareTo(ddate) == 1) {
  // ddateが昔
} else if (today.compareTo(ddate)  == 0) {
  // ddateが今日と同じ
} else if (today.compareTo(ddate) == -1) {
  // ddateが未来
}

年月日曜日取得

Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DATE);
int week = cal.get(Calendar.DAY_OF_WEEK);
int h = cal.get(now.HOUR_OF_DAY);//時を取得
int m = cal.get(now.MINUTE);     //分を取得
int s = cal.get(now.SECOND);      //秒を取得

hh:mm:ssから秒数取得

Calendarが推奨

try {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    Date date = sdf.parse("01:02:03");
    cal.setTime(date);
    System.out.println("calendar hour=" + cal.get(Calendar.HOUR_OF_DAY));
    System.out.println("calendar minute=" + cal.get(Calendar.MINUTE));
    System.out.println("calendar second=" + cal.get(Calendar.SECOND));
    System.out.println("total sec=" + (cal.get(Calendar.HOUR_OF_DAY) * 3600 + cal.get(Calendar.MINUTE) * 60 + cal.get(Calendar.SECOND))); // 3723
    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss.SSS");
    Date datems = sdf2.parse("01:02:03.123");
    cal.setTime(datems);
    System.out.println("calendar hour=" + cal.get(Calendar.HOUR_OF_DAY));
    System.out.println("calendar minute=" + cal.get(Calendar.MINUTE));
    System.out.println("calendar second=" + cal.get(Calendar.SECOND));
    System.out.println("total sec=" + (cal.get(Calendar.HOUR_OF_DAY) * 3600 + cal.get(Calendar.MINUTE) * 60 + cal.get(Calendar.SECOND))); // 3723
} catch(ParseException e) {
    e.printStackTrace();
}

参考:https://docs.oracle.com/javase/jp/7/api/java/util/Date.html

Dateは非推奨

try {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    Date date = sdf.parse("01:02:03");
    System.out.println("second=" + date.getSeconds());
    System.out.println("min=" + date.getMinutes());
    System.out.println("hour=" + date.getHours());
    System.out.println("total sec=" + (date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()));
    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss.SSS");
    Date datems = sdf2.parse("01:02:03.123");
    System.out.println("second=" + datems.getSeconds());
    System.out.println("min=" + datems.getMinutes());
    System.out.println("hour=" + datems.getHours());
    System.out.println("total sec=" + (datems.getHours() * 3600 + datems.getMinutes() * 60 + datems.getSeconds()));
} catch(ParseException e) {
    e.printStackTrace();
}