ソースコードの整形ルールの設定
Eclipse→ウィンドウ→設定→Java→コードスタイル→ フォーマッター→編集
自動適用の設定
Eclipse→ウィンドウ→設定→Java→エディター→ 保管アクション
Eclipse→ウィンドウ→設定→Java→コードスタイル→
自動適用の設定
Eclipse→ウィンドウ→設定→Java→エディター→
日 | 月 | 火 | 水 | 木 | 金 | 土 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
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;
}
}