如何将 java.util.Date 转换为 java.sql.Date?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/530012/
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
How to convert java.util.Date to java.sql.Date?
提问by David Ackerman
I am trying to use a java.util.Date
as input and then creating a query with it - so I need a java.sql.Date
.
我正在尝试使用 ajava.util.Date
作为输入,然后用它创建一个查询 - 所以我需要一个java.sql.Date
.
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
我很惊讶地发现它不能隐式或显式地进行转换 - 但我什至不知道我将如何做到这一点,因为 Java API 对我来说仍然是相当新的。
采纳答案by Basil Bourque
tl;dr
tl;博士
How to convert java.util.Date to java.sql.Date?
如何将 java.util.Date 转换为 java.sql.Date?
Don't.Both classes are outmoded.
别。这两个类都过时了。
- Use java.timeclasses instead of legacy
java.util.Date
&java.sql.Date
with JDBC 4.2 or later. - Convert to/from java.time if inter-operating with code not yet updated to java.time.
- 在 JDBC 4.2 或更高版本中使用java.time类而不是 legacy
java.util.Date
&java.sql.Date
。 - 如果与尚未更新为 java.time 的代码互操作,则转换为 java.time 或从 java.time 转换。
Example query with PreparedStatement
.
myPreparedStatement.setObject(
… , // Specify the ordinal number of which argument in SQL statement.
myJavaUtilDate.toInstant() // Convert from legacy class `java.util.Date` (a moment in UTC) to a modern `java.time.Instant` (a moment in UTC).
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to a particular time zone, to determine a date. Instantiating a `ZonedDateTime`.
.toLocalDate() // Extract a date-only `java.time.LocalDate` object from the date-time `ZonedDateTime` object.
)
Replacements:
更换:
Instant
instead ofjava.util.Date
Both represent a moment in UTC. but now with nanoseconds instead of milliseconds.LocalDate
instead ofjava.sql.Date
Both represent a date-only value without a time of day and without a time zone.
Instant
而不是java.util.Date
Both 代表 UTC 中的一个时刻。但现在用纳秒而不是毫秒。LocalDate
而不是java.sql.Date
Both 表示没有时间和时区的仅日期值。
Details
细节
If you are trying to work with date-only values (no time-of-day, no time zone), use the LocalDate
class rather than java.util.Date
.
如果您尝试使用仅限日期的值(无时间、无时区),请使用LocalDate
类而不是java.util.Date
.
java.time
时间
In Java 8 and later, the troublesome old date-time classes bundled with early versions of Java have been supplanted by the new java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backportand further adapted to Android in ThreeTenABP.
在 Java 8 及更高版本中,与早期 Java 版本捆绑在一起的麻烦的旧日期时间类已被新的java.time 包所取代。请参阅Oracle 教程。许多功能已被后移植到Java 6和7在ThreeTen-反向移植和在进一步适于到Android ThreeTenABP。
A SQL data typeDATE
is meant to be date-only, with no time-of-day and no time zone. Java never had precisely such a class? until java.time.LocalDate
in Java 8. Let's create such a value by getting today's date according to a particular time zone (time zone is important in determining a date as a new day dawns earlier in Paris than in Montréal, for example).
一个SQL数据类型DATE
,就是要日期而已,没有时区没有时间的日和。Java 从未有过这样的类?直到java.time.LocalDate
在 Java 8 中。让我们通过根据特定时区获取今天的日期来创建这样的值(例如,时区对于确定日期很重要,因为巴黎比蒙特利尔更早开始新的一天)。
LocalDate todayLocalDate = LocalDate.now( ZoneId.of( "America/Montreal" ) ); // Use proper "continent/region" time zone names; never use 3-4 letter codes like "EST" or "IST".
At this point, we may be done. If your JDBC drivercomplies with JDBC 4.2 spec, you should be able to pass a LocalDate
via setObject
on a PreparedStatement
to store into a SQL DATE field.
至此,我们可能就大功告成了。如果您的JDBC驱动程序符合以下法规JDBC 4.2规范,你应该能够传递一个LocalDate
通过setObject
一个PreparedStatement
存储到一个SQL日期字段。
myPreparedStatement.setObject( 1 , localDate );
Likewise, use ResultSet::getObject
to fetch from a SQL DATE column to a Java LocalDate
object. Specifying the class in the second argument makes your code type-safe.
同样,用于ResultSet::getObject
从 SQL DATE 列提取到 JavaLocalDate
对象。在第二个参数中指定类使您的代码类型安全。
LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );
In other words, this entire Question is irrelevant under JDBC 4.2or later.
换句话说,整个问题在 JDBC 4.2或更高版本下都无关紧要。
If your JDBC driver does not perform in this manner, you need to fall back to converting to the java.sql types.
如果您的 JDBC 驱动程序不以这种方式执行,您需要回退到转换为 java.sql 类型。
Convert to java.sql.Date
转换为 java.sql.Date
To convert, use new methods added to the old date-time classes. We can call java.sql.Date.valueOf(…)
to convert a LocalDate
.
要进行转换,请使用添加到旧日期时间类的新方法。我们可以调用java.sql.Date.valueOf(…)
转换一个LocalDate
.
java.sql.Date sqlDate = java.sql.Date.valueOf( todayLocalDate );
And going the other direction.
并走向另一个方向。
LocalDate localDate = sqlDate.toLocalDate();
Converting from java.util.Date
转换自 java.util.Date
While you should avoid using the old date-time classes, you may be forced to when working with existing code. If so, you can convert to/from java.time.
虽然您应该避免使用旧的日期时间类,但在使用现有代码时可能会被迫使用。如果是这样,您可以转换为/从 java.time。
Go through the Instant
class, which represents a moment on the timeline in UTC. An Instant
is similar in idea to a java.util.Date
. But note that Instant
has a resolution up to nanosecondswhile java.util.Date
has only millisecondsresolution.
完成Instant
课程,它代表 UTC 时间线上的一个时刻。AnInstant
在思想上与 a 相似java.util.Date
。但请注意,Instant
分辨率高达纳秒,而java.util.Date
只有毫秒分辨率。
To convert, use new methods added to the old classes. For example, java.util.Date.from( Instant )
and java.util.Date::toInstant
.
要进行转换,请使用添加到旧类中的新方法。例如,java.util.Date.from( Instant )
和java.util.Date::toInstant
。
Instant instant = myUtilDate.toInstant();
To determine a date, we need the context of a time zone. For any given moment, the date varies around the globe by time zone. Apply a ZoneId
to get a ZonedDateTime
.
要确定日期,我们需要时区的上下文。对于任何给定时刻,日期在全球各地因时区而异。申请 aZoneId
以获得ZonedDateTime
.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();
? The java.sql.Date class pretends to be date-only without a time-of-day but actually doesa time-of-day, adjusted to a midnight time. Confusing? Yes, the old date-time classes are a mess.
? java.sql.Date 类假装是没有时间的仅日期,但实际上是一天中的时间,调整为午夜时间。令人困惑?是的,旧的日期时间类是一团糟。
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- java.time类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by David Ackerman
Nevermind....
没关系....
public class MainClass {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
}
}
explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm
回答by mauretto
With the other answer you may have troubles with the time info (compare the dates with unexpected results!)
使用其他答案,您可能会在时间信息方面遇到问题(将日期与意外结果进行比较!)
I suggest:
我建议:
java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
回答by Benjamin Ndugga
If you are usgin Mysql a date column can be passed a String representation of this date
如果您使用的是 Mysql,则可以向日期列传递此日期的字符串表示形式
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
所以我使用 DateFormatter 类对其进行格式化,然后在 sql 语句或准备好的语句中将其设置为字符串
here is the code illustration:
这是代码说明:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
字符串日期 = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement
//然后在你的sql语句中传递这个日期
回答by Donovan Thomson
Method for comparing 2 dates (util.date or sql.date)
比较 2 个日期的方法(util.date 或 sql.date)
public static boolean isSameDay(Date a, Date b) {
Calendar calA = new GregorianCalendar();
calA.setTime(a);
Calendar calB = new GregorianCalendar();
calB.setTime(b);
final int yearA = calA.get(Calendar.YEAR);
final int monthA = calA.get(Calendar.MONTH);
final int dayA = calA.get(Calendar.DAY_OF_YEAR);
final int yearB = calB.get(Calendar.YEAR);
final int monthB = calB.get(Calendar.MONTH);
final int dayB = calB.get(Calendar.DAY_OF_YEAR);
return yearA == yearB && monthA == monthB && dayA == dayB;
}
回答by Krishna
Here the example of converting Util Date to Sql date and ya this is one example what i am using in my project might be helpful to you too.
这是将 Util Date 转换为 Sql date 的示例,这是我在项目中使用的一个示例,可能对您也有帮助。
java.util.Date utilStartDate = table_Login.getDob();(orwhat ever date your give form obj)
java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());(converting date)
回答by kapil das
try with this
试试这个
public static String toMysqlDateStr(Date date) {
String dateForMySql = "";
if (date == null) {
dateForMySql = null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateForMySql = sdf.format(date);
}
return dateForMySql;
}
回答by UmeshA
i am using the following code please try it out
我正在使用以下代码,请尝试一下
DateFormat fm= new SimpleDateFormatter();
specify the format of the date you want
for example "DD-MM_YYYY"
or 'YYYY-mm-dd'
then use the java Date datatype as
例如,指定您想要的日期格式,"DD-MM_YYYY"
或者'YYYY-mm-dd'
然后使用 java Date 数据类型作为
fm.format("object of java.util.date");
then it will parse your date
然后它会解析你的日期
回答by chetan
This function will return a converted SQL date from java date object.
此函数将从 java 日期对象返回转换后的 SQL 日期。
public java.sql.Date convertJavaDateToSqlDate(java.util.Date date) {
return new java.sql.Date(date.getTime());
}
回答by Tanmay kumar shaw
This function will return a converted SQL date from java date object.
此函数将从 java 日期对象返回转换后的 SQL 日期。
public static java.sql.Date convertFromJAVADateToSQLDate(
java.util.Date javaDate) {
java.sql.Date sqlDate = null;
if (javaDate != null) {
sqlDate = new Date(javaDate.getTime());
}
return sqlDate;
}
回答by Emmanuel Angelo.R
You can use this method to convert util date to sql date,
您可以使用此方法将 util 日期转换为 sql 日期,
DateUtilities.convertUtilDateToSql(java.util.Date)