「Java」compareTo()メソッドでTimestampオブジェクトを比較するサンプル

2020年11月4日

説明
1.public Date parse(String source)throws ParseException
指定された文字列の先頭からテキストを解析して日付を生成します。メソッドは指定された文字列のテキスト全体に使用されない場合もあります。
2.public long getTime()
Dateオブジェクトで表される、1970年1月1日00:00:00 GMTからのミリ秒数を返します。
3.public int compareTo(Timestamp ts)
このTimestampオブジェクトを指定されたTimestampオブジェクトと比較します。
Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.java;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class TimeStampComPare {
private static final String PTN = "yyyy-MM-dd";
public static void main(String[] args) throws ParseException {
String strA = "2020-10-20 16:21:54";
String strB = "2020-10-21 16:21:54";
SimpleDateFormat fmt = new SimpleDateFormat(PTN);
//timestamp
Timestamp tmA = new Timestamp(fmt.parse(strA).getTime());
Timestamp tmB = new Timestamp(fmt.parse(strB).getTime());
System.out.println("timestampA:\n" + tmA);
System.out.println("timestampB:\n" + tmB);
int result = tmA.compareTo(tmB);
System.out.println("timestampA and timestampB compare result:\n" + result);
}
}
package com.arkgame.study.java; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; public class TimeStampComPare { private static final String PTN = "yyyy-MM-dd"; public static void main(String[] args) throws ParseException { String strA = "2020-10-20 16:21:54"; String strB = "2020-10-21 16:21:54"; SimpleDateFormat fmt = new SimpleDateFormat(PTN); //timestamp Timestamp tmA = new Timestamp(fmt.parse(strA).getTime()); Timestamp tmB = new Timestamp(fmt.parse(strB).getTime()); System.out.println("timestampA:\n" + tmA); System.out.println("timestampB:\n" + tmB); int result = tmA.compareTo(tmB); System.out.println("timestampA and timestampB compare result:\n" + result); } }
package com.arkgame.study.java;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class TimeStampComPare {

      private static final String PTN = "yyyy-MM-dd";

      public static void main(String[] args) throws ParseException {
            String strA = "2020-10-20 16:21:54";
            String strB = "2020-10-21 16:21:54";

            SimpleDateFormat fmt = new SimpleDateFormat(PTN);
            //timestamp
            Timestamp tmA = new Timestamp(fmt.parse(strA).getTime());
            Timestamp tmB = new Timestamp(fmt.parse(strB).getTime());

            System.out.println("timestampA:\n" + tmA);
            System.out.println("timestampB:\n" + tmB);

            int result = tmA.compareTo(tmB);
            System.out.println("timestampA and timestampB compare result:\n" + result);
      }

}

実行結果
timestampA:
2020-10-20 00:00:00.0
timestampB:
2020-10-21 00:00:00.0
timestampA and timestampB compare result:
-1

Java

Posted by arkgame