[英]How to convert java.util.Date to java.sql.Date?
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
.我正在尝试使用
java.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 对我来说仍然相当新。
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
链接是http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm
How to convert java.util.Date to java.sql.Date?
如何将 java.util.Date 转换为 java.sql.Date?
Don't.别。
Both Date
classes are outmoded.两个
Date
类都过时了。 Sun , Oracle , and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes. Sun 、 Oracle和JCP社区在几年前随着JSR 310定义java.time类的一致采用而放弃了那些遗留的日期时间类。
java.util.Date
& java.sql.Date
with JDBC 4.2 or later.java.util.Date
使用java.time类而不是旧的java.util.Date
和java.sql.Date
。 Legacy![]() |
Modern![]() |
Conversion![]() |
---|---|---|
java.util.Date |
java.time.Instant |
java.util.Date.toInstant() java.util.Date.from( Instant ) |
java.sql.Date |
java.time.Date |
java.sql.Date.toLocalDate() java.sql.Date.valueOf( LocalDate ) |
Example query with PreparedStatement
.使用
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 of java.util.Date
Instant
而不是java.util.Date
LocalDate
instead of java.sql.Date
LocalDate
而不是java.sql.Date
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
。
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 .在 Java 8 及更高版本中,与早期 Java 版本捆绑在一起的麻烦的旧日期时间类已被新的java.time 包所取代。 See Oracle Tutorial .
请参阅Oracle 教程。 Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP .
许多功能已被后移植到Java 6和7在ThreeTen-反向移植和在进一步适于到Android ThreeTenABP 。
A SQL data type DATE
is meant to be date-only, with no time-of-day and no time zone. SQL 数据类型
DATE
意味着只有日期,没有时间和时区。 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).在 Java 8 中的
java.time.LocalDate
之前,Java 从未有过这样的类†。让我们通过根据特定时区获取今天的日期来创建这样一个值(时区对于确定日期很重要,因为巴黎的新一天更早到来比在蒙特利尔,例如)。
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 driver complies 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 规范,您应该能够通过
PreparedStatement
上的setObject
传递LocalDate
以存储到 SQL DATE 字段中。
myPreparedStatement.setObject( 1 , localDate );
Likewise, use ResultSet::getObject
to fetch from a SQL DATE column to a Java LocalDate
object.同样,使用
ResultSet::getObject
从 SQL DATE 列获取 Java LocalDate
对象。 Specifying the class in the second argument makes your code type-safe .在第二个参数中指定类使您的代码类型安全。
LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );
In other words, this entire Question is irrelevant under JDBC 4.2 or 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 类型。
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();
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.通过
Instant
类,它代表 UTC 时间线上的一个时刻。 An Instant
is similar in idea to a java.util.Date
. Instant
在思想上类似于java.util.Date
。 But note that Instant
has a resolution up to nanoseconds while java.util.Date
has only milliseconds resolution.但请注意,
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
.应用
ZoneId
以获得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 does a time-of-day, adjusted to a midnight time. † java.sql.Date 类假装是没有时间的仅日期,但实际上是一天中的时间,调整为午夜时间。 Confusing?
令人困惑? Yes, the old date-time classes are a mess.
是的,旧的日期时间类是一团糟。
The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
, Calendar
, & SimpleDateFormat
.这些类取代麻烦的老传统日期时间类,如
java.util.Date
, Calendar
,和SimpleDateFormat
。
To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程。 And search Stack Overflow for many examples and explanations.
并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .
规范是JSR 310 。
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式的Joda-Time项目建议迁移到java.time类。
You may exchange java.time objects directly with your database.您可以直接与您的数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later.
使用符合JDBC 4.2或更高版本的JDBC 驱动程序。 No need for strings, no need for
java.sql.*
classes.不需要字符串,不需要
java.sql.*
类。 Hibernate 5 & JPA 2.2 support java.time . Hibernate 5 & JPA 2.2 支持java.time 。
Where to obtain the java.time classes?从哪里获得 java.time 类?
The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目用额外的类扩展了 java.time。 This project is a proving ground for possible future additions to java.time.
该项目是未来可能添加到 java.time 的试验场。 You may find some useful classes here such as
Interval
, YearWeek
, YearQuarter
, and more .您可以在这里找到一些有用的类,比如
Interval
, YearWeek
, YearQuarter
,和更多。
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);
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());
}
Converting java.util.Date
to java.sql.Date
will lose hours, minutes and seconds.将
java.util.Date
转换为java.sql.Date
将丢失小时、分钟和秒。 So if it is possible, I suggest you to use java.sql.Timestamp
like this:所以如果可能的话,我建议你像这样使用
java.sql.Timestamp
:
prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));
For more info, you can check this question .有关更多信息,您可以查看此问题。
In my case of picking date from JXDatePicker (java calender) and getting it stored in database as SQL Date type, below works fine ..在我从 JXDatePicker(Java 日历)中选择日期并将其作为 SQL 日期类型存储在数据库中的情况下,下面的工作正常..
java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());
where pickedDate is object of JXDatePicker其中pickDate是JXDatePicker的对象
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;
}
Format your java.util.Date first.首先格式化您的 java.util.Date。 Then use the formatted date to get the date in java.sql.Date
然后使用格式化的日期获取java.sql.Date中的日期
java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate= java.sql.Date.valueOf(stringDate);
java.sql.Date sqlDate = new java.sql.Date(javaDate.getTime());
这里 javaDate 是 java.util.Date 的实例
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)
I am a novice: after much running around this worked.我是一个新手:经过多次运行后,这行得通。 Thought might be useful
想法可能有用
String bufDt = bDOB.getText(); //data from form
DateFormat dF = new SimpleDateFormat("dd-MM-yyyy"); //data in form is in this format
Date bbdt = (Date)dF.parse(bufDt); // string data is converted into java util date
DateFormat dsF = new SimpleDateFormat("yyyy-MM-dd"); //converted date is reformatted for conversion to sql.date
String ndt = dsF.format(bbdt); // java util date is converted to compatible java sql date
java.sql.Date sqlDate= java.sql.Date.valueOf(ndt); // finally data from the form is convered to java sql. date for placing in database
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;
}
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;
}
I think the best way to convert is:我认为最好的转换方法是:
static java.sql.Timestamp SQLDateTime(Long utilDate) {
return new java.sql.Timestamp(utilDate);
}
Date date = new Date();
java.sql.Timestamp dt = SQLDateTime(date.getTime());
If you want to insert the dt
variable into an SQL table you can do:如果要将
dt
变量插入 SQL 表,可以执行以下操作:
insert into table (expireAt) values ('"+dt+"');
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然后它会解析你的日期
您可以使用此方法将 util 日期转换为 sql 日期,
DateUtilities.convertUtilDateToSql(java.util.Date)
I was trying the following coding that worked fine.我正在尝试以下编码效果很好。
java.util.Date utilDate = new java.util.Date();
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate);java.sql.Date sqlDate = new java.sql.Date(utilDate);
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语句中传递这个日期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.