logo

Java の Date クラス (例付き)

Date クラスは、ミリ秒の精度で特定の瞬間を表します。 java.util パッケージの Date クラスは、Serializable Cloneable および Comparable インターフェイスを実装します。 Java で日付と時刻を処理するためのコンストラクターとメソッドを提供します。 コンストラクター
    日付(): 現在の日付と時刻を表す日付オブジェクトを作成します。 日付(長いミリ秒): 1970 年 1 月 1 日 00:00:00 GMT からの指定されたミリ秒の日付オブジェクトを作成します。 日付(int 年 int 月 int 日付) Date(int 年 int 月 int 日付 int 時間 int 分) Date(int 年 int 月 int 日付 int 時間 int 分 int 秒) 日付(文字列) 注記 : The last 4 constructors of the Date class are Deprecated. Java
    // Java program to demonstrate constuctors of Date import java.util.*; public class Main {  public static void main(String[] args)  {  Date d1 = new Date();  System.out.println('Current date is ' + d1);  Date d2 = new Date(2323223232L);  System.out.println('Date represented is '+ d2 );  } } 
    Output:
    Current date is Tue Jul 12 18:35:37 IST 2016 Date represented is Wed Jan 28 02:50:23 IST 1970 
    重要な方法
      ブール値 after(日付 date) :現在の日付が指定された日付より後であるかどうかをテストします。 ブール値 before(日付 date) :現在の日付が指定された日付より前かどうかをテストします。 int CompareTo(Date date) :現在の日付と指定された日付を比較します。引数 Date が Date と等しい場合は 0 を返します。 Date が Date 引数より前の場合は 0 より小さい値。日付が Date 引数より後の場合は 0 より大きい値。 長い getTime(): この Date オブジェクトで表される 1970 年 1 月 1 日 00:00:00 GMT からのミリ秒数を返します。 void setTime(長時間): 現在の日付と時刻を指定した時刻に変更します。
    Java
    // Program to demonstrate methods of Date class import java.util.*; public class Main {  public static void main(String[] args)  {  // Creating date  Date d1 = new Date(2000 11 21);  Date d2 = new Date(); // Current date  Date d3 = new Date(2010 1 3);  boolean a = d3.after(d1);  System.out.println('Date d3 comes after ' +  'date d2: ' + a);  boolean b = d3.before(d2);  System.out.println('Date d3 comes before '+  'date d2: ' + b);  int c = d1.compareTo(d2);  System.out.println(c);  System.out.println('Miliseconds from Jan 1 '+  '1970 to date d1 is ' + d1.getTime());  System.out.println('Before setting '+d2);  d2.setTime(204587433443L);  System.out.println('After setting '+d2);  } } 
    Output:
    Date d3 comes after date d2: true Date d3 comes before date d2: false 1 Miliseconds from Jan 1 1970 to date d1 is 60935500800000 Before setting Tue Jul 12 13:13:16 UTC 2016 After setting Fri Jun 25 21:50:33 UTC 1976