Java 日期轉換 格式化輸入/輸出日期 中文星期 教學 示範

LocalDate
// 將輸入的日期字串轉換為 LocalDate物件
String inputDateString = "20220101";
LocalDate localDate = LocalDate.parse(inputDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));

// LocalDate物件 輸出為日期字串
String localDateString = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(localDate);
System.out.println(localDateString); //2022/01/01

// 輸出星期
String weekString = DateTimeFormatter.ofPattern("EEEE", Locale.TAIWAN).format(localDate);
System.out.println(weekString); // 星期六

// Date
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
System.out.println(date); // Sat Jan 01 00:00:00 CST 2022
Date
// 將輸入的日期字串轉換為 Date物件
String inputDateString = "2022/01/01 08:30";
SimpleDateFormat inputSimpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date date = inputSimpleDateFormat.parse(inputDateString);

// Date物件 輸出為日期字串
SimpleDateFormat outputSimpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
System.out.println(outputSimpleDateFormat.format(date)); // 2022/01/01 08:30:00.000

// 輸出星期
SimpleDateFormat outputWeekSimpleDateFormat = new SimpleDateFormat("EEEE", Locale.TAIWAN);
System.out.println(outputWeekSimpleDateFormat.format(date)); // 星期六
System.out.println(outputWeekSimpleDateFormat.format(date).substring(2)); //

// LocalDate
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(localDate); // 2022-01-01

Github Gist

留言