Get the Current Date and Time in Java – 在Java中获取当前日期和时间

最后修改: 2016年 10月 11日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

This quick article describes how we may get the current date, current time and current time stamp in Java 8.

这篇文章描述了我们如何在Java 8中获得当前日期、当前时间和当前时间戳。

2. Current Date

2.当前日期

First, let’s use java.time.LocalDate to get the current system date:

首先,让我们使用java.time.LocalDate来获取当前的系统日期。

LocalDate localDate = LocalDate.now();

To get the date in any other timezone we can use LocalDate.now(ZoneId):

要获得其他时区的日期,我们可以使用LocalDate.now(ZoneId)

LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));

We can also use java.time.LocalDateTime to get an instance of LocalDate:

我们也可以使用java.time.LocalDateTime来获得LocalDate的实例:

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();

3. Current Time

3.当前时间

With java.time.LocalTime, let’s retrieve the current system time:

通过java.time.LocalTime,让我们检索一下当前的系统时间。

LocalTime localTime = LocalTime.now();

To get the current time in a specific time zone, we can use LocalTime.now(ZoneId):

要获得一个特定时区的当前时间,我们可以使用LocalTime.now(ZoneId)

LocalTime localTime = LocalTime.now(ZoneId.of("GMT+02:30"));

We can also use java.time.LocalDateTime to get an instance of LocalTime:

我们还可以使用java.time.LocalDateTime来获取LocalTime的实例:

LocalDateTime localDateTime = LocalDateTime.now();
LocalTime localTime = localDateTime.toLocalTime();

4. Current Timestamp

4.当前的时间戳

Use java.time.Instant to get a time stamp from the Java epoch. According to the JavaDoc, “epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z, where instants after the epoch have positive values:

使用java.time.Instant来获取来自Java纪元的时间戳。根据JavaDoc,”纪元-秒是从1970-01-01T00:00:00Z这个标准的Java纪元开始测量的,其中纪元之后的时刻有正值。

Instant instant = Instant.now();
long timeStampMillis = instant.toEpochMilli();

We may obtain the number of epoch-seconds seconds:

我们可以得到纪元-秒的数量。

Instant instant = Instant.now();
long timeStampSeconds = instant.getEpochSecond();

5. Conclusion

5.结论

In this tutorial we’ve focused using java.time.* to get the current date, time and time stamp.

在本教程中,我们主要使用java.time.*来获取当前的日期、时间和时间戳。

As always, the code for the article is available over on GitHub.

一如既往,该文章的代码可在GitHub上找到。