黑馬程序員:與日期和時間相關的幾個類

最常用的幾個類: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);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章