java中的日期时间数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6516320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:32:54  来源:igfitidea点击:

datetime datatype in java

javadatetimestamp

提问by akshay

Which data type can I use in Java to hold the current date as well as time?. I want to store the datetime in a db as well as having a field in the java bean to hold that.

我可以在 Java 中使用哪种数据类型来保存当前日期和时间?。我想将日期时间存储在 db 中,并在 java bean 中有一个字段来保存它。

is it java.util.Date?

java.util.Date吗?

回答by Jon Skeet

java.util.Daterepresents an instantin time, with no reference to a particular time zone or calendar system. It does hold both date and time though - it's basically a number of milliseconds since the Unix epoch.

java.util.Date代表一个瞬间,没有参考特定的时区或日历系统。不过它确实保存了日期和时间——它基本上是自 Unix 时代以来的几毫秒。

Alternatively you can use java.util.Calendarwhich doesknow about both of those things.

或者,您可以使用java.util.Calendarwhich确实了解这两件事。

Personally I would stronglyrecommend you use Joda Timewhich is a muchricher date/time API. It allows you to express your data much more clearly, with types for "just dates", "just local times", "local date/time", "instant", "date/time with time zone" etc. Most of the types are also immutable, which is a hugebenefit in terms of code clarity.

我个人强烈建议您使用Joda Time,它是一个丰富的日期/时间 API。它允许您更清楚地表达您的数据,包括“仅日期”、“仅本地时间”、“本地日期/时间”、“即时”、“带时区的日期/时间”等类型。大多数类型也是不可变的,这在代码清晰度方面是一个巨大的好处。

回答by Rupok

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

private String getDateTime() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    return dateFormat.format(date);
}

回答by Srikanth Venkatesh

You can use Calendar.

您可以使用日历。

     Calendar rightNow = Calendar.getInstance();

Calendar

日历

Date4j alternative to Date, Calendar, and related Java classes

Date4j 替代日期、日历和相关 Java 类

回答by nogridbag

+1 the recommendation for Joda-time. If you plan on doing anything more than a simple Hello World example, I suggest reading this:

+1 对 Joda 时间的推荐。如果您打算做的不仅仅是一个简单的 Hello World 示例,我建议您阅读以下内容:

Daylight saving time and time zone best practices

夏令时和时区最佳实践

回答by OscarRyz

Depends on the RDBMS or even the JDBC driver.

取决于 RDBMS 甚至 JDBC 驱动程序。

Most of the times you can use java.sql.Timestampmost of the times along with a prepared statement:

大多数情况下,您可以将java.sql.Timestamp与准备好的语句一起使用:

pstmt.setTimestamp( index, new Timestamp( yourJavaUtilDateInstance.getTime() );

回答by dmiadan

I used this import:

我使用了这个导入:

import java.util.Date;

And declared my variable like this:

并像这样声明我的变量:

Date studentEnrollementDate;

回答by Tarrasch

Since Java 8, it seems like the java.timestandard library is the way to go. From Joda timeweb page:

从 Java 8 开始,java.time标准库似乎是要走的路。来自Joda 时间网页:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - 替代该项目的 JDK 的核心部分。



Back to your question. Were you to use Java 8, I think you want LocalDateTime. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.

回到你的问题。如果您使用 Java 8,我想您想要LocalDateTime. 因为它包含日期和时间,但不知道时区或任何参考时间点,例如 unix 纪元。

回答by Basil Bourque

java.time

时间

The java.time framework built into Java 8 and later supplants both the old date-time classes bundled with the earliest versions of Java and the Joda-Time library. The java.time classes have been back-ported to Java 6 & 7 and to Android.

Java 8 及更高版本中内置的 java.time 框架取代了与最早版本的 Java 和 Joda-Time 库捆绑在一起的旧日期时间类。java.time 类已经向后移植到 Java 6 & 7 和 Android。

The Instantclass represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant类表示UTC时间线与纳秒的分辨率上一会儿。

Instant instant = Instant.now();

Apply an offset-from-UTC (a number of hours and possible minutes and seconds) to get an OffsetDateTime.

应用与 UTC 的偏移量(小时数和可能的分钟数和秒数)以获取OffsetDateTime.

ZoneOffset offset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , offset );

Better yet is applying a full time zone which is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).

更好的是应用一个完整的时区,它是一个偏移量加上一组处理异常的规则,如夏令时 (DST)。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Database

数据库

Hopefully the JDBC drivers will be updated to work directly with the java.time classes. Until then we must use the java.sql classes to move date-time values to/from the database. But limit your use of the java.sql classes to the chore of database transit. Do not use them for business logic. As part of the old date-time classes they are poorly designed, confusing, and troublesome.

希望 JDBC 驱动程序将更新为直接使用 java.time 类。在此之前,我们必须使用 java.sql 类将日期时间值移入/移出数据库。但是将您对 java.sql 类的使用限制为数据库传输的繁琐工作。不要将它们用于业务逻辑。作为旧日期时间类的一部分,它们设计不佳、令人困惑且麻烦。

Use new methods added to the old classes to convert to/from java.time. Look for to…and valueOfmethods.

使用添加到旧类的新方法与 java.time 进行转换。寻找to…valueOf方法。

Use the java.sql.Timestampclass for date-time values.

将该java.sql.Timestamp类用于日期时间值。

java.sql.Timestamp ts = java.sql.Timestamp.valueOf( instant );

And going the other direction…

走向另一个方向……

Instant instant = ts.toInstant();

For date-time data you virtually always want the TIMESTAMP WITH TIME ZONEdata type rather than WITHOUTwhen designing your table columns in your database.

对于日期时间数据,您几乎总是需要TIMESTAMP WITH TIME ZONE数据类型,而不是WITHOUT在设计数据库中的表列时。