Get the Current Date Prior to Java 8 – 获取Java 8之前的当前日期

最后修改: 2019年 11月 18日

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

1. Introduction

1.绪论

In legacy systems, we might need to work with dates when neither the new date and time API nor the highly recommended Joda-Time library is available.

在传统系统中,当新的日期和时间API和强烈推荐的Joda-Time库都无法使用时,我们可能需要处理日期。

In this short tutorial, we’re going to take a look at several approaches to see how to get the current date in pre-Java 8 systems.

在这个简短的教程中,我们将看一下几种方法,看看如何在Java 8之前的系统中获得当前日期

2. System Time

2.系统时间

When all we need is a single numeric value representing the current date and time, we can use the system time. To get the number of milliseconds passed since January 1, 1970 00:00:00 GMT we can use the currentTimeMillis method which returns a long:

当我们只需要一个代表当前日期和时间的单一数字值时,我们可以使用系统时间。要获得自1970年1月1日00:00:00 GMT以来的毫秒数,我们可以使用currentTimeMillis方法,它返回一个long

long elapsedMilliseconds = System.currentTimeMillis();

When we want to measure elapsed time with greater precision, we can use the nanoTime method. This will return the value of nanoseconds that have passed from a fixed but arbitrary moment.

当我们想要更精确地测量过往时间时,我们可以使用nanoTime方法。这将返回从一个固定但任意的时刻开始所经过的纳秒值。

This arbitrary time is the same for all calls inside the JVM, so the value returned is useful only for computing the difference in elapsed nanoseconds between multiple calls of nanoTime:

这个任意时间对JVM内部的所有调用都是一样的,所以返回的值只对计算多次调用nanoTime之间经过的纳秒数的差异有用。

long elapsedNanosecondsStart = System.nanoTime();
long elapsedNanoseconds = System.nanoTime() - elapsedNanosecondsStart;

3. The java.util Package

3.java.util

Using classes from the java.util package, we can represent a moment in time, usually by the milliseconds elapsed since January 1, 1970 00:00:00 GMT.

使用java.util包中的类,我们可以表示一个时间点,通常是指从1970年1月1日00:00:00 GMT起经过的毫秒。

3.1. java.util.Date

3.1. java.util.Date

We can represent a specific date and time by using a Date object. This contains a precision of milliseconds and the time zone information.

我们可以通过使用一个Date对象来表示一个特定的日期和时间。这包含了毫秒的精度和时区信息

While there are many constructors available, the simplest way to create a Date object representing the current date in the local time zone is to use the basic constructor:

虽然有许多构造函数可用,但创建代表本地时区当前日期的Date对象的最简单方法是使用基本构造函数。

Date currentUtilDate = new Date();

Let’s now create a Date object for a specific date and time. We could use the aforementioned constructors and simply pass the milliseconds value.

现在让我们为一个特定的日期和时间创建一个Date对象。我们可以使用前述的构造函数,并简单地传递毫秒值。

Alternatively, we can use the SimpleDateFormat class to convert a String value to an actual Date object:

另外,我们可以使用SimpleDateFormat类来将一个String值转换为一个实际的Date对象。

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date customUtilDate = dateFormatter.parse("30-01-2020 10:11:12");

We can use a wide range of date patterns to suit our needs.

我们可以使用广泛的日期模式来满足我们的需求。

3.2. java.util.Calendar

3.2. java.util.Calendar

A Calendar object can do what a Date does, and it’s better for date arithmetic computations since it can also take a Locale. We can specify the Locale as a geographic, political, or cultural region.

Calendar对象可以做Date做的事情,而且它更适合于日期算术计算,因为它还可以接受Locale。我们可以将Locale指定为一个地理、政治或文化区域。

To get the current date, with no TimeZone or Locale specified, we can use the getInstance method:

要获得当前日期,在没有指定TimeZoneLocale时,我们可以使用getInstance方法。

Calendar currentUtilCalendar = Calendar.getInstance();

And for Calendar to Date conversion, we can simply use the getTime method:

而对于CalendarDate的转换,我们可以简单地使用getTime方法。

Date currentDate = Calendar.getInstance().getTime();

As a fun fact, the GregorianCalendar class is the implementation of the most used calendar in the world.

作为一个有趣的事实,GregorianCalendar类是世界上使用最多的日历实现。

4. The java.sql Package

4.java.sql

Next, we’ll explore three extensions of the java.util.Date class that represents the equivalent SQL objects.

接下来,我们将探讨java.util.Date类的三个扩展,它们代表了同等的SQL对象。

4.1. java.sql.Date

4.1java.sql.Date

With a java.sql.Date object, we don’t have access to time zone information, and the precision is truncated at the day level. To represent today, we can use the constructor that takes a long representation of milliseconds:

对于java.sql.Date对象,我们无法访问时区信息,而且精度在日级别被截断了。为了表示今天,我们可以使用构造函数,它需要一个long表示的毫秒。

Date currentSqlDate = new Date(System.currentTimeMillis());

As before, for a specific date, we can use the SimpleDateFormat class to convert to a java.util.Date first and then get the milliseconds using the getTime method. Then, we can pass this value to the java.sql.Date constructor.

像以前一样,对于一个特定的日期,我们可以使用SimpleDateFormat类首先转换为java.util.Date,然后使用getTime方法获得毫秒。然后,我们可以将这个值传递给java.sql.Date构造函数。

We can simply use the valueOf method when the String representation of a Date matches the yyyy-[m]m-[d]d pattern:

DateString表示法与Dateyyyy-[m]m-[d]d模式匹配时,我们可以简单地使用valueOf方法。

Date customSqlDate = Date.valueOf("2020-01-30");

4.2. java.sql.Time

4.2. java.sql.Time

The java.sql.Time object offers access to the hour, minute, and second information — once again, with no access to a time zone. Let’s get the current Time using milliseconds representation:

java.sql.Time对象提供了对时、分、秒信息的访问–再一次,没有对时区的访问。让我们使用毫秒表示法来获取当前的Time

Time currentSqlTime = new Time(System.currentTimeMillis());

To specify a time using the valueOf method, we can pass in a value matching the hh:mm:ss pattern:

要使用valueOf方法指定一个时间,我们可以传入一个与hh:mm:ss模式匹配的值。

Time customSqlTime = Time.valueOf("10:11:12");

4.3. java.sql.Timestamp

4.3. java.sql.Timestamp

In this last section, we’ll combine both the SQL Date and Time information using the Timestamp class. This allows us to have precision down to nanoseconds.

在最后一节,我们将使用Timestamp类将SQL的DateTime信息结合起来。这使得我们可以获得精确到纳秒的精确度

Let’s create a Timestamp object by once again passing a long value for the current number of milliseconds to the constructor:

让我们创建一个Timestamp对象,再次向构造函数传递一个long值,表示当前的毫秒数。

Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());

Finally, let’s create a new custom Timestamp using the valueOf method with the required yyyy-[m]m-[d]d hh:mm:ss[.f…] pattern:

最后,让我们使用valueOf方法创建一个新的自定义Timestamp,并使用所需的yyyy-[m]m-[d]d hh:mm:ss[.f..]模式。

Timestamp customSqlTimestamp = Timestamp.valueOf("2020-1-30 10:11:12.123456789");

5. Conclusion

5.总结

In this short tutorial, we’ve seen how to get the current date and the date for a given instant without the use of Java 8 or any external libraries.

在这个简短的教程中,我们已经看到了如何在不使用Java 8或任何外部库的情况下获得当前日期和某一时刻的日期。

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

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