[英]What is the most efficient way to create Date Object in Java
I am creating Date
object in java. 我正在用Java创建
Date
对象。
First way: By using Calender 第一种方式:使用日历
Date today = Calendar.getInstance().getTime();
Second way: 第二种方式:
with Date class 与日期类
Date today1 = new Date();
Which one is most effective way here? 哪一种是最有效的方法?
Since Java 8 you should go for LocalDateTime or LocalDate: 从Java 8开始,您应该使用LocalDateTime或LocalDate:
LocalDateTime timePoint = LocalDateTime.now(
); // The current date and time
LocalDate.of(2012, Month.DECEMBER, 12); // from values
LocalDate theDate = timePoint.toLocalDate(); // or
theDate = LocalDate.now(); //
Fromt the documentation: 从文档:
[For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren't thread-safe, leading to potential concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code.
[例如,现有类(例如java.util.Date和SimpleDateFormatter)不是线程安全的,这会导致用户潜在的并发问题,这是普通开发人员在编写日期处理代码时不会期望的。
Some of the date and time classes also exhibit quite poor API design.
一些日期和时间类还表现出相当差的API设计。 For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.] 1
例如,java.util.Date中的年份从1900开始,月份从1开始,而几天从0开始-不太直观。] 1
If you have to decide between the two. 如果您必须在两者之间做出决定。 Take the
new Date()
. 采用
new Date()
。 As the Calendar.getInstance().getTime()
would create a Calendar
instance which you could not use afterwards. 由于
Calendar.getInstance().getTime()
将创建一个Calendar
实例,以后您将无法使用它。
You can use this too! 您也可以使用它! Date newDate = new GregorianCalendar(year, month, day).getTime();
日期newDate =新的GregorianCalendar(年,月,日).getTime();
Within your options, I will prefer the first alternative. 在您的选择范围内,我将首选第一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.