1. Overview
1.概述
Creating a date in Java had been redefined with the advent of Java 8. Besides, the new Date & Time API from the java.time package can be used with ease relative to the old one from the java.util package. In this tutorial, we’ll see how it makes a huge difference.
随着Java 8的出现,在Java中创建一个日期已经被重新定义。此外,相对于来自java.time包的旧API,来自java.util包的新Date & Time API可以轻松地使用。在本教程中,我们将看到它是如何产生巨大差异的。
The LocalDate class from the java.time package helps us achieve this. LocalDate is an immutable, thread-safe class. Moreover, a LocalDate can hold only date values and cannot have a time component.
LocalDate类来自java.time包,可以帮助我们实现这一目标。LocalDate是一个不可变的、线程安全的类。此外,LocalDate只能持有日期值,不能有时间成分。
Let’s now see all the variants of creating one with values.
现在让我们看看用价值创建一个的所有变体。
2. Create a Custom LocalDate with of()
2.用of()创建一个自定义LocalDate
Let’s look at a few ways of creating a LocalDate representing January 8, 2020. We can create one by passing values to the factory method of:
让我们看一下创建代表2020年1月8日的LocalDate的几种方法。我们可以通过向工厂方法of传递值来创建一个。
LocalDate date = LocalDate.of(2020, 1, 8);
The month can also be specified using the Month enum:
也可以使用Month枚举来指定月份。
LocalDate date = LocalDate.of(2020, Month.JANUARY, 8)
We can also try to get it using the epoch day:
我们也可以尝试用纪元日来得到它。
LocalDate date = LocalDate.ofEpochDay(18269);
And finally, let’s create one with the year and day-of-year values:
最后,让我们创建一个带有年份和年月日值的数据。
LocalDate date = LocalDate.ofYearDay(2020, 8);
3. Create a LocalDate by Parsing a String
3.通过解析一个字符串来创建一个LocalDate
The last option is to create a date by parsing a string. We can use the parse method with only a single argument to parse a date in the yyyy-mm-dd format:
最后一个选择是通过解析一个字符串来创建一个日期。我们可以使用只有一个参数的parse方法来解析一个yyyy-mm-dd格式的日期。
LocalDate date = LocalDate.parse("2020-01-08");
We can also specify a different pattern to get one using the DateTimeFormatter class as the second parameter of the parse method:
我们还可以指定一个不同的模式,使用DateTimeFormatter类作为parse方法的第二个参数来获得一个。
LocalDate date = LocalDate.parse("8-Jan-2020", DateTimeFormatter.ofPattern("d-MMM-yyyy"));
4. Conclusion
4.总结
In this article, we’ve seen all the variants of creating a LocalDate with values in Java. The Date & Time API articles can help us understand more.
在这篇文章中,我们看到了在Java中创建带有数值的LocalDate的所有变体。Date & Time API文章可以帮助我们了解更多。
The examples are available over on GitHub.
这些例子可以在GitHub上找到over。