最常用的几个类:Date ,DateFormat,Calendar ,Time,TimerTask
* Calendar类 //日期字段的操作 是抽象基类
-Calendar.add() //在某日期基础上增加 若干天 若干年等
-Calendar.get() //获得 年月日时分秒的值
-Calendar.set() //修改日期字段的值
-Calendar.getInstance() // 静态方法 返回Calendar子类的 对象
-GregorianCalendar // Calendar的子类
例如:
public static void main(String[] args) {
Calendar cld=Calendar.getInstance();
System.out.println((cld.get(Calendar.YEAR)+"年"+cld.get(Calendar.MONTH)+"月"+
cld.get(Calendar.DAY_OF_MONTH)+"日"+cld.get(Calendar.HOUR_OF_DAY)+":"+
cld.get(Calendar.MINUTE)+":"+cld.get(Calendar.SECOND)+""));
cld.add(cld.DAY_OF_YEAR,315 );
System.out.println((cld.get(Calendar.YEAR)+"年"+cld.get(Calendar.MONTH)+"月"+
cld.get(Calendar.DAY_OF_MONTH)+"日"+cld.get(Calendar.HOUR_OF_DAY)+":"+
cld.get(Calendar.MINUTE)+":"+cld.get(Calendar.SECOND)+""));
}
* Date类
java.text.DateFormat//将日期以指定的格式输出,或将特定的格式日期转换为Date的实例对象(抽象类)
java.text.SimpleDateFormat子类
例如:
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日");
try {
Date d= sdf1.parse("2011-03-12");
System.out.print(sdf2.format(d));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
*Time和TimerTask
schedule方法有以下的重载形式:
schedule(TimeTask task,long delay) //隔多长时间后执行 task
schedule(TimeTask task,Date time) //在什么时间执行 task
schedule(TimeTask task,long delay,long period)//隔多长时间开始定期执行task,period(间隔)
schedule(TimeTask task,Date firstTime,long period) //在什么时间开始定期执行task
TimeTask类实现了Runnable接口,要执行的任务由它里面的run()方法完成
例如: 编写一段代码,让程序启动windows自带的计算机程序后立即结束。
class MyTimerTask extends TimerTask {
private Timer tm = null;
public MyTimerTask(Timer tm) {
this.tm = tm;
public void run() {
try {
Runtime.getRuntime().exec("calc.exe");
} catch (Exception e) {
e.printStackTrace();
}
tm.cancel();
}}
Timer tm = new Timer();
tm.schedule(new MyTimerTask(tm), 10000);