如何在Java中获取当前日期和时间
在这篇文章中,你会发现几个例子,在Java中获取当前日期、当前时间、当前日期和时间、特定时区的当前日期和时间。
在Java中获取当前日期
import java.time.LocalDate;
public class CurrentDateTimeExample {
public static void main(String[] args) {
// Current Date
LocalDate currentDate = LocalDate.now();
System.out.println("Current Date: " + currentDate);
}
}
在Java中获取当前时间
import java.time.LocalTime;
public class CurrentDateTimeExample {
public static void main(String[] args) {
// Current Time
LocalTime currentTime = LocalTime.now();
System.out.println("Current Time: " + currentTime);
}
}
在Java中获取当前日期和时间
import java.time.LocalDateTime;
public class CurrentDateTimeExample {
public static void main(String[] args) {
// Current Date and Time
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current Date & time: " + currentDateTime);
}
}
在Java中获取特定时区的当前日期和时间
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class CurrentDateTimeExample {
public static void main(String[] args) {
// Current Date and Time in a given Timezone
ZonedDateTime currentNewYorkDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(currentNewYorkDateTime);
}
}
