Java:如何获取当前时间

本文介绍了在Java 8中使用java.time.* API获取当前日期时间的方法,如LocalDate.now()和Instant.now(),同时也提到了传统API中的new Date()和Calendar.getInstance()及其格式化方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文介绍如何从新的 Java 8 java.time.* 中获取当前日期时间,如 Localdate、LocalTime、LocalDateTime、ZonedDateTime、Instant 以及旧的日期时间 API,如 Date 和 Calendar。

新旧API:

对于新的 Java 8 的java.time.* API,我们可以使用 .now() 获取当前日期时间并使用 DateTimeFormatter 对其进行格式化。 对于传统的日期时间 API,我们可以使用 new Date() 和 Calendar.getInstance() 来获取当前日期时间并使用 SimpleDateFormat 对其进行格式化。

对于 java.time.LocalDate,使用 LocalDate.now()获取当前时间:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate));            // 2021/03/22
对于 java.time.localTime,使用 LocalTime.now():
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalTime localTime = LocalTime.now();
System.out.println(dtf.format(localTime));            // 16:37:15
对于 java.time.LocalDateTime,使用 LocalDateTime.now()
  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss");
  LocalDateTime now = LocalDateTime.now();
  System.out.println(dtf.format(now));                  //  2021/03/22 16:37:15
对于 java.time.ZonedDateTime,使用 ZonedDateTime.now()
  // get current date-time, with system default time zone
  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss");
  ZonedDateTime now = ZonedDateTime.now();
  System.out.println(dtf.format(now));                  // 2021/03/22 16:37:15
  System.out.println(now.getOffset());                  // +08:00

  // get current date-time, with a specified time zone
  ZonedDateTime japanDateTime = now.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
  System.out.println(dtf.format(japanDateTime));        // 2021/03/22 17:37:15
  System.out.println(japanDateTime.getOffset());        // +09:00

对于 java.time.Instant,使用 Instant.now()

  Instant now = Instant.now();

  // convert Instant to ZonedDateTime
  DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss");
  ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, ZoneId.systemDefault());
  System.out.println(dtfDateTime.format(zonedDateTime));

对于 java.util.Date,使用 new Date()

  DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  Date date = new Date();
  System.out.println(dateFormat.format(date));           // 2021/03/22 16:37:15

对于 java.util.Calendar,使用 Calendar.getInstance()

  DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  Calendar cal = Calendar.getInstance();
  System.out.println(dateFormat.format(cal.getTime()));  // 2021/03/22 16:37:15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值