在Java中,您可以使用LocalDateTime
類來處理日期和時(shí)間。要控制時(shí)間,您需要執(zhí)行以下操作:
LocalDateTime
對(duì)象: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
對(duì)象轉(zhuǎn)換為其他日期時(shí)間格式,可以使用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
對(duì)象的時(shí)間。