Java LocalDate/Date input and output example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package app.ruyut.ruyutdemo; | |
import org.junit.jupiter.api.Test; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.time.LocalDate; | |
import java.time.ZoneId; | |
import java.time.format.DateTimeFormatter; | |
import java.util.Date; | |
import java.util.Locale; | |
public class UtilityTest { | |
@Test | |
public void localDateTest() { | |
// 將輸入的日期字串轉換為 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 | |
} | |
@Test | |
public void dateTest() throws ParseException { | |
// 將輸入的日期字串轉換為 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment