在Java中,您可以使用LocalDateTime
類來處理日期和時間。要控制時間,您需要執行以下操作:
LocalDateTime
對象:import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Current date and time: " + dateTime);
}
}
dateTime = dateTime.withHour(10).withMinute(30).withSecond(15).withNano(0);
System.out.println("Modified date and time: " + dateTime);
LocalDate
類:import java.time.LocalDate;
LocalDate date = LocalDate.of(2022, 6, 15);
LocalDateTime dateTimeWithSpecificDate = LocalDateTime.of(date, LocalTime.now());
System.out.println("Date with current time: " + dateTimeWithSpecificDate);
LocalDateTime
對象轉換為其他日期時間格式,可以使用DateTimeFormatter
類:import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = dateTime.format(formatter);
System.out.println("Formatted date and time: " + formattedDateTime);
通過這些方法,您可以控制LocalDateTime
對象的時間。