java - 在Java中创建日期对象最有效的方法是什么

标签 java date

我正在java中创建Date对象。

第一种方式: 通过使用日历

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

第二种方式:

带有日期类

Date today1 = new Date();

哪一种是最有效的方法?

最佳答案

从 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(); // 

来自文档:

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

Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.]1

关于java - 在Java中创建日期对象最有效的方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30504516/

相关文章:

java - 带有 JAR 的 WAR 项目中的 "could not create Vfs.Dir"

java - 与 Spring 一起使用时,Hibernate 将空值插入到表中

java - 在多个 fragment 中显示日期

javascript - 根据javascript中的时区更新时间

javascript - 无效日期 : Converting UTC to local

java - 我可以序列化 ArrayList 而不序列化其中包含的对象吗?

java - 在 Java 中如何避免这种删除错误?

javascript 日期,获取过去 12 个月

java - Java/MySQL 中没有时间或时区组件的日期

Java 监控工具,可以查看 "real time"处的堆栈跟踪