Javaには日付と時間(時刻)のデータを扱うための高度な機能があります.
ただ,初心者には理解し難いものもあるので,ここでは素朴な例を挙げます.
Javaのクラスライブラリに Date というクラスがあり,このクラスのインスタンスを new で生成すると,現在の日付と時刻に関するデータを保持するオブジェクトができます.
下の例 “DateTest1.java” では年,月,日,曜日,時,分,秒を手軽に取り出すメソッドを備えたクラス Date2(Dateクラスの拡張)を実装しています.
import java.util.*;
import java.text.*;
class Date2 extends Date {
/*--------------------------------------*
* constructor *
*--------------------------------------*/
Date2(int year, int month, int day) {
}
Date2() {
}
/*--------------------------------------*
* methods *
*--------------------------------------*/
/* Date2 -> Year */
public int Date2Year() {
int y;
SimpleDateFormat f;
f = new SimpleDateFormat("yyyy");
y = Integer.parseInt(f.format(this));
return( y );
}
/* Date2 -> Month */
public int Date2Month() {
int m;
SimpleDateFormat f;
f = new SimpleDateFormat("MM");
m = Integer.parseInt(f.format(this));
return( m );
}
/* Date2 -> Day */
public int Date2Day() {
int d;
SimpleDateFormat f;
f = new SimpleDateFormat("dd");
d = Integer.parseInt(f.format(this));
return( d );
}
/* Date2 -> Week day */
public String Date2WDay() {
String wd;
SimpleDateFormat f;
f = new SimpleDateFormat("E");
wd = f.format(this);
return( wd );
}
/* Date2 -> Hour */
public int Date2Hour() {
int h;
SimpleDateFormat f;
f = new SimpleDateFormat("hh");
h = Integer.parseInt(f.format(this));
return( h );
}
/* Date2 -> Minute */
public int Date2Min() {
int m;
SimpleDateFormat f;
f = new SimpleDateFormat("mm");
m = Integer.parseInt(f.format(this));
return( m );
}
/* Date2 -> Second */
public int Date2Sec() {
int s;
SimpleDateFormat f;
f = new SimpleDateFormat("ss");
s = Integer.parseInt(f.format(this));
return( s );
}
}
class DateTest1 {
public static void main( String argv[] ) {
int y,m,day,h,min,sec;
String wd;
Date2 d = new Date2(); // 現在の日付,時刻の取得
y = d.Date2Year(); // 年の取得
m = d.Date2Month(); // 月の取得
day = d.Date2Day(); // 日の取得
wd = d.Date2WDay(); // 曜日の取得
h = d.Date2Hour(); // 時の取得
min = d.Date2Min(); // 分の取得
sec = d.Date2Sec(); // 秒の取得
System.out.printf("%d/%d/%d (%s), %s:%s:%s\n",
y,m,day,wd,h,min,sec);
}
}
このプログラムを実行すると,その時の日付と時刻を表示します.