「Java」Date型からTimestamp型への変換サンプル

環境
Spring Tool Suite 4
JavaSE17

書式
Date 変数名A = new Date();
Timestamp 変数名B = new Timestamp(変数名A.getTime());
public long getTime()
Date オブジェクトで表される、1970 年 1 月 1 日 00:00:00 GMT からのミリ秒数を返します。
戻り値:
この日付で表される、1970 年 1 月 1 日 00:00:00 GMT からのミリ秒数

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
public class SimpleDateFormatDemo {
public static void main(String[] args) throws ParseException {
// Date型を取得
Date dt = new Date();
System.out.println("Date型の結果: " + dt);
// Timestampに変換
Timestamp tsp = new Timestamp(dt.getTime());
System.out.println("Date型からtimestamp型への変換結果 : " + tsp);
}
}
package com.arkgame.study; import java.sql.Timestamp; import java.text.ParseException; import java.util.Date; public class SimpleDateFormatDemo { public static void main(String[] args) throws ParseException { // Date型を取得 Date dt = new Date(); System.out.println("Date型の結果: " + dt); // Timestampに変換 Timestamp tsp = new Timestamp(dt.getTime()); System.out.println("Date型からtimestamp型への変換結果 : " + tsp); } }
package com.arkgame.study;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;

public class SimpleDateFormatDemo {

      public static void main(String[] args) throws ParseException {
            // Date型を取得
            Date dt = new Date();
            System.out.println("Date型の結果: " + dt);

            // Timestampに変換
            Timestamp tsp = new Timestamp(dt.getTime());
            System.out.println("Date型からtimestamp型への変換結果 : " + tsp);

      }

}

実行結果
Date型の結果: Sat Apr 23 20:42:51 JST 2022
Date型からtimestamp型への変換結果 : 2022-04-23 20:42:51.479

Java

Posted by arkgame