简体   繁体   English

用Java创建日期对象的最有效方法是什么

[英]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.

相关问题 从Java Date对象中删除时间的最有效方法是什么? - What's the most efficient way to strip out the time from a Java Date object? 用Java创建HashMap副本 - 最有效的方法是什么? - Create a HashMap copy in Java - What's the most efficient way? 从 java 列表 object 创建 XML 的最有效方法 - Most Efficient way to create XML from java List object 在Java对象中获取项目子集的最有效方法是什么? - What is the most efficient way to get a subset of items in a Java Object? 在 java 中创建 JSON 字符串的最有效方法 - Most Efficient way to create JSON String in java 在java中模拟倒计时的最有效方法是什么? - What is the most efficient way to simulate a countdown in java? Java — 同步 ArrayList 的最有效方法是什么? - Java — What is the most efficient way to synchronize an ArrayList? 传递Java对象的最有效方法? - Most efficient way to pass a Java object around? 在内存和性能方面,在 Java 中每秒打印格式化的日期+时间的最有效方法是什么? - What is the most efficient way in terms of memory and performance to print a formatted date+time every second in Java? 检查Date对象和Calendar对象是否在同一个月的最有效方法 - Most efficient way of checking if Date object and Calendar object are in the same month
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM