在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
对象的时间。