2018年03月23日

Java 日付から文字列、文字列から日付へ変換

定番ですが、Javaで日付と文字列の相互変換のメモです。
LocalDateTime型とDate型の2パターンです。
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class MyClass {

    private static String DATETIME_FORMAT = "yyyy年MM月dd日 HH時mm分ss秒";

    public static void main(String... arg) {

        // LocalDateTime型の変換
        System.out.println(dateTimeToString(LocalDateTime.now()));
        System.out.println(parseDateTime("2018年03月23日 20時34分45秒"));

        // Date型の変換
        System.out.println(dateToString(new Date()));
        System.out.println(parseDate("2018年03月23日 20時34分45秒"));
    }

    /**
     * LocalDateTime型を文字列へ変換
     * @param datetime 日付時刻
     * @return 日付時刻から変換した文字列
     */
    public static String dateTimeToString(LocalDateTime datetime) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATETIME_FORMAT);
        return dtf.format(datetime);
    }

    /**
     * 文字列をLocalDateTime型へ変換
     * @param str 文字列
     * @return 文字列から変換した日付時刻
     */
    public static LocalDateTime parseDateTime(String str) {
        LocalDateTime ldt = null;
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATETIME_FORMAT);
        try {
            ldt = LocalDateTime.parse(str, dtf);
        } catch (DateTimeException e) {
            // Date型に変換できないものはnull
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ldt;
    }

    /**
     * Date型を文字列へ変換
     * @param date 日付時刻
     * @return 日付時刻から変換した文字列
     */
    public static String dateToString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
        return sdf.format(date);
    }

    /**
     * 文字列をDate型へ変換
     * @param str 文字列
     * @return 文字列から変換した日付時刻
     */
    public static Date parseDate(String str) {
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
        try {
            date = sdf.parse(str);
        } catch (java.text.ParseException e) {
            // Date型に変換できないものはnull
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }
}
タグ:JAVA
posted by Hiro at 20:35| Comment(0) | プログラム
この記事へのコメント
コメントを書く
お名前:

メールアドレス:

ホームページアドレス:

コメント: