facebook twitter hatena line email

「Java/日付」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(ページの作成:「==日付比較== SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm"); Date ddate = sdf.parse("2012-10-10 10:10"); Date today = new Date(); if (today.compa...」)
 
(年月日曜日取得)
行20: 行20:
 
  int m = cal.get(now.MINUTE);    //分を取得
 
  int m = cal.get(now.MINUTE);    //分を取得
 
  int s = cal.get(now.SECOND);      //秒を取得
 
  int s = cal.get(now.SECOND);      //秒を取得
 +
 +
==hh:mm:ssから秒数取得==
 +
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()));

2018年11月6日 (火) 19:10時点における版

日付比較

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から秒数取得

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()));