Java SimpleDateFormatクラスを使ってString型からTimestamp型に変換する方法

環境
Java-SE 17
Eclipse 2022-06 M2 (4.24.0 M2)

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(日付の形式);
String変数名 =値
Timestamp resTimestamp = new Timestamp(simpleDateFormat.parse(String型変数名).getTime());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(日付の形式); String変数名 =値 Timestamp resTimestamp = new Timestamp(simpleDateFormat.parse(String型変数名).getTime());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(日付の形式);
String変数名 =値
Timestamp resTimestamp = new Timestamp(simpleDateFormat.parse(String型変数名).getTime());

SimpleDateFormatを使ってString型からTimestamp型への変換します。

使用例

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 ArkgameTest {
// 日付の形式
private static final String FMT = "yyyy/MM/dd HH:mm:ss";
public static void main(String[] args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FMT);
// 文字列の宣言
String str = "2023/02/13 12:34:56";
// String型->Timestamp型
Timestamp resTimestamp = new Timestamp(simpleDateFormat.parse(str).getTime());
System.out.println("String型からTimestamp型への変換結果:\n" + resTimestamp);
}
}
package com.arkgame.study; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; public class ArkgameTest { // 日付の形式 private static final String FMT = "yyyy/MM/dd HH:mm:ss"; public static void main(String[] args) throws ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FMT); // 文字列の宣言 String str = "2023/02/13 12:34:56"; // String型->Timestamp型 Timestamp resTimestamp = new Timestamp(simpleDateFormat.parse(str).getTime()); System.out.println("String型からTimestamp型への変換結果:\n" + resTimestamp); } }
package com.arkgame.study;

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

public class ArkgameTest {
      // 日付の形式
      private static final String FMT = "yyyy/MM/dd HH:mm:ss";

      public static void main(String[] args) throws ParseException {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FMT);
            // 文字列の宣言
            String str = "2023/02/13 12:34:56";
            // String型->Timestamp型
            Timestamp resTimestamp = new Timestamp(simpleDateFormat.parse(str).getTime());
            System.out.println("String型からTimestamp型への変換結果:\n" + resTimestamp);

      }

}

実行結果
String型からTimestamp型への変換結果:
2023-02-13 12:34:56.0

Java

Posted by arkgame