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

環境
Spring Tool Suite 4
JavaSE17

関数
1.parse(String text, ParsePosition pos)
文字列からテキストを解析してDateを生成します。
2.getTime()
このTimestampオブジェクトで表される、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.text.SimpleDateFormat;
public class SimpleDateFormatDemo {
// フォーマット形式
public static final String FMT = "yyyy/MM/dd HH:mm:ss";
public static void main(String[] args) throws ParseException {
// 文字列
String str = "2022/04/23 20:29:07";
System.out.println("文字列: " + str);
SimpleDateFormat sdf = new SimpleDateFormat(FMT);
// Timestampオブジェクト生成
Timestamp timestamp = new Timestamp(sdf.parse(str).getTime());
System.out.println("StringからTimestampへ変換結果:" + timestamp);
}
}
package com.arkgame.study; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; public class SimpleDateFormatDemo { // フォーマット形式 public static final String FMT = "yyyy/MM/dd HH:mm:ss"; public static void main(String[] args) throws ParseException { // 文字列 String str = "2022/04/23 20:29:07"; System.out.println("文字列: " + str); SimpleDateFormat sdf = new SimpleDateFormat(FMT); // Timestampオブジェクト生成 Timestamp timestamp = new Timestamp(sdf.parse(str).getTime()); System.out.println("StringからTimestampへ変換結果:" + timestamp); } }
package com.arkgame.study;

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

public class SimpleDateFormatDemo {

      // フォーマット形式
      public static final String FMT = "yyyy/MM/dd HH:mm:ss";

      public static void main(String[] args) throws ParseException {
            // 文字列
            String str = "2022/04/23 20:29:07";
            System.out.println("文字列: " + str);
            SimpleDateFormat sdf = new SimpleDateFormat(FMT);
            
            // Timestampオブジェクト生成
            Timestamp timestamp = new Timestamp(sdf.parse(str).getTime());
            System.out.println("StringからTimestampへ変換結果:" + timestamp);
      }

}

実行結果
文字列: 2022/04/23 20:29:07
StringからTimestampへ変換結果:2022-04-23 20:29:07.0

Java

Posted by arkgame