Java SimpleDateFormatクラスを使用して日付をフォーマットするサンプル

環境
JavaSE 17
Eclipse 2022

構文
1.public static long currentTimeMillis()
ミリ秒で表される現在の時間を返します。
2.SimpleDateFormat(String pattern)
指定されたパターンとデフォルトのFORMATロケールのデフォルト日付フォーマット記号を使ってSimpleDateFormatを構築します。
3.public StringBuffer format(Date date,StringBuffer toAppendTo,FieldPosition pos)
指定されたDateを日付/時間文字列にフォーマットし、指定されたStringBufferに結果を付加します。

使用例

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.DateFormat;
import java.text.SimpleDateFormat;
public class TimeDemo {
// 日付の形式
private static String PATTERN = "yyyyMMddHHmmss";
public static void main(String[] args) {
// 現在日付のtimestampを取得
Timestamp tmp = getNowTimestamp();
// DateFormat変数の宣言
DateFormat format = null;
format = new SimpleDateFormat(PATTERN);
String currenttime = format.format(tmp);
System.out.println("現在日付: " + currenttime);
}
/**
* 現在日付timestampを返す
*
* @return
*/
public static Timestamp getNowTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
}
package com.arkgame.study; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; public class TimeDemo { // 日付の形式 private static String PATTERN = "yyyyMMddHHmmss"; public static void main(String[] args) { // 現在日付のtimestampを取得 Timestamp tmp = getNowTimestamp(); // DateFormat変数の宣言 DateFormat format = null; format = new SimpleDateFormat(PATTERN); String currenttime = format.format(tmp); System.out.println("現在日付: " + currenttime); } /** * 現在日付timestampを返す * * @return */ public static Timestamp getNowTimestamp() { return new Timestamp(System.currentTimeMillis()); } }
package com.arkgame.study;

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

public class TimeDemo {

      // 日付の形式
      private static String PATTERN = "yyyyMMddHHmmss";

      public static void main(String[] args) {
            // 現在日付のtimestampを取得
            Timestamp tmp = getNowTimestamp();

            // DateFormat変数の宣言
            DateFormat format = null;
            format = new SimpleDateFormat(PATTERN);

            String currenttime = format.format(tmp);
            System.out.println("現在日付: " + currenttime);

      }

      /**
       * 現在日付timestampを返す
       * 
       * @return
       */
      public static Timestamp getNowTimestamp() {
            return new Timestamp(System.currentTimeMillis());
      }
}

実行結果
現在日付: 20221228171545

Java

Posted by arkgame