Javaexamples-date-add-time

提供:Dev Guides
移動先:案内検索

Javaの例-日付に時刻を追加

問題の説明

日付に時間(日、年、秒)を追加する方法は?

溶液

次の例は、Calenderのadd()メソッドを使用して日付に時間を追加する方法を示しています。

import java.util.*;

public class Main {
   public static void main(String[] args) throws Exception {
      Date d1 = new Date();
      Calendar cl = Calendar. getInstance();
      cl.setTime(d1);
      System.out.println("today is " + d1.toString());
      cl. add(Calendar.MONTH, 1);
      System.out.println("date after a month will be " + cl.getTime().toString() );
      cl. add(Calendar.HOUR, 70);
      System.out.println("date after 7 hrs will be " + cl.getTime().toString() );
      cl. add(Calendar.YEAR, 3);
      System.out.println("date after 3 years will be " + cl.getTime().toString() );
   }
}

結果

上記のコードサンプルは、次の結果を生成します。

today is Mon Jun 22 02:47:02 IST 2009
date after a month will be Wed Jul 22 02:47:02 IST 2009
date after 7 hrs will be Wed Jul 22 09:47:02 IST 2009
date after 3 years will be Sun Jul 22 09:47:02 IST 2012