API
记录Java工程中用于获取当前时间的API方法
System.currentTimeMillis()
- 作用:返回自1970年1月1日00:00:00 GMT以来的毫秒数。
- 返回值类型:
long
。 - 使用场景:主要用于时间间隔计算、性能监测和时间戳记录等场景。
示例:
long currentTimeMillis = System.currentTimeMillis();
System.out.println("Current Time in Milliseconds: " + currentTimeMillis);
new Date()
- 作用:创建一个表示当前日期和时间的
Date
对象。 - 返回值类型:
java.util.Date
。 - 使用场景:用于表示具体的时间点,可以与其他日期和时间类进行相互转换和操作。
示例:
Date currentDate = new Date();
System.out.println("Current Date: " + currentDate);
System.currentTimeMillis()
主要用于获取时间戳和计算时间间隔。new Date()
主要用于生成具体的日期和时间对象,以便进一步操作。
LocalDateTime
表示日期和时间(不包含时区信息)。
示例:
import java.time.LocalDateTime;
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentDateTime);
LocalDate
表示仅日期(不包含时间和时区)。
示例:
import java.time.LocalDate;
LocalDate currentDate = LocalDate.now();
System.out.println("Current Date: " + currentDate);
LocalTime
表示仅时间(不包含日期和时区)。
示例:
import java.time.LocalTime;
LocalTime currentTime = LocalTime.now();
System.out.println("Current Time: " + currentTime);
Instant
表示时间戳(自1970年1月1日00:00:00 UTC以来的毫秒数)。
示例:
import java.time.Instant;
Instant currentInstant = Instant.now();
System.out.println("Current Instant: " + currentInstant);
ZonedDateTime
表示带时区的日期和时间。
示例:
import java.time.ZonedDateTime;
ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
System.out.println("Current ZonedDateTime: " + currentZonedDateTime);
Calendar
一种较老的日期和时间处理方法,不建议新项目中使用,但在维护遗留代码时可能会遇到。
示例:
import java.util.Calendar;
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date: " + calendar.getTime());
Clock
(Java8+)
通过它可以获取系统的当前时间,用来替代System.currentTimeMillis()
。
示例:
import java.time.Clock;
Clock clock = Clock.systemDefaultZone();
Instant instant = clock.instant();
System.out.println("Current Instant from Clock: " + instant);