获取当前时间的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);
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值