Date.toString() - sql 与 util 日期
我需要从 Date
对象中删除时间。这是我的尝试,
代码:
System.out.println("date " + dbDate);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("formatter.format(dbDate) " + formatter.format(dbDate));
System.out.println("final " + formatter.parse(formatter.format(dbDate)));
输出:
date 2011-12-03 23:59:59.0
formatter.format(dbDate) 2011-12-03
final Sat Dec 03 00:00:00 IST 2011
我希望最终日期显示在 2011-12-03
中。但在转换 toString()
后,该 Date
的格式不同。我缺少一些东西。请帮忙。
更新:
在我的应用程序中,我有两种不同的方法来获取dbDate
。 EXPIRY_DATE
列是 DATE
类型。
第一个查询使用 dbDate = (java.util.Date) rs.getDate("EXPIRY_DATE");。
对于此 dbDate
,System.out.println("date " + dbDate);
给出 date 2011-12-03
第二个查询使用 dbDate = rs.getTimestamp("EXPIRY_DATE");
对于此 dbDate
,System.out.println("date " + dbDate);
给出日期 2011-12-03 23:59:59.0
。
这是我的问题。由于我认为 toString()
出现了问题,因此我没有提及完整的问题。
解决方案:
我没有选择避免使用java.sql.Date
,因为我的应用程序方法有多种用途。
我尝试了下面的方法并工作了,
dbDate = new java.sql.Date(dbDate.getTime());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你不能。
java.util.Date
对象包含日期和时间。它的 toString() 也在 固定格式。如果您想在没有时间的情况下将其表示给人类,那么您需要像您已经做的那样将其转换为String
。或者,如果您打算将其存储在没有时间的数据库中(如变量名称dbDate
中的db
部分所示),那么您需要将其转换为java.sql.Date
。更新 根据您的更新,
ResultSet#getDate()
返回java.sql.Date
的实例,而不是java.util .Date
(但它是java.util.Date
的子类,这就是为什么不必要的转换起作用的原因;请注意,转换与转换不同,真正的转换将是 <代码>新java.util.Date(dbDate.getTime()))。正如您可以在 中阅读的java.sql.Date
的toString()
方法的javadoc,它确实是yyyy-MM-dd
格式。因此,您的具体问题是您将
java.sql.Date
与java.util.Date
混淆了,并且您误解了java 的内部工作原理.util.Date
并被toString()
方法误导。一切都按预期进行。相关:
You can't. The
java.util.Date
object contains both the date and time. ItstoString()
is also in a fixed format. If you want to represent it without time to humans, then you need to convert it to aString
like as you already did. Or, if you intend to store it in the DB without the time (as thedb
part in the variable namedbDate
suggests), then you need to convert it tojava.sql.Date
.Update as per your update, the
ResultSet#getDate()
returns an instance ofjava.sql.Date
, notjava.util.Date
(but it is a subclass ofjava.util.Date
, that's why the unnecessary cast worked; please note that casting is not the same as converting, a real conversion would benew java.util.Date(dbDate.getTime())
). As you can read in the javadoc of thetoString()
method ofjava.sql.Date
, it's indeed inyyyy-MM-dd
format.So, your concrete problem is that you're confusing
java.sql.Date
withjava.util.Date
and that you're misgrasping the internal workings ofjava.util.Date
and been mislead by thetoString()
method. Everything is working as intented.Related:
如果您想要删除
Date
对象的时间部分:Calendar
删除Date
对象的时间部分。正如这个问题中指出的:Java Date 截止时间信息。如果您只想获取
String
表示形式,而没有Date
对象的时间部分:SimpleDateFormat.format()
。您不能让Date.toString()
返回不同的值,它将始终使用该模式。看看它的 源代码。If what you want to do is remove the time part of the
Date
object:Calendar
to remove the time part of yourDate
object. As pointed out in this question: Java Date cut off time information.If you only want to obtain a
String
representation without the time part of theDate
object:SimpleDateFormat.format()
. You can't makeDate.toString()
return a different value, it will always use that pattern. Look at its source code.当您最后一次调用
formatter.parse()
时,您将返回一个Date
对象;然后,串联对Date.toString()
进行隐式调用:此调用返回的格式是 JVM 中设置的区域设置的默认格式。您必须了解的是
Date
对象不知道字符串表示形式,在内部它只是 inte 的聚合When you last call
formatter.parse()
you get back aDate
object; the concatenation then makes an implicit call toDate.toString()
: the format returned by this call is the default for the locale set in the JVM.What you must understand is that the
Date
object has no knowledge of the string representation, internally it's just an aggregate of inte对于那些遇到与我相同问题的人,我也遇到了类似的问题,我写了这个条目:
问题是从数据库获取并传递到 Web 客户端的日期值的格式为
yyyy-mm-dd
但在第一个条目的应用程序中没有数据库值,因此我们创建日期对象并将该值传递给 Web 客户端,该客户端为我们提供时间戳值。将传递给 Web 客户端的值必须采用日期格式,因此SimpleDateFormat
对我来说不是一个好的选择因此,从这篇文章中我了解了 java.sql.date 和 java.util.date 的区别,然后创建第一个对象,
该对象为
yyyy-mm-dd
提供值code>toString 方法。I have encountered similar problem for those who encounters the same problem as mine I write this entry:
The problem is the date value that is taken from database and passed to the web client is in format
yyyy-mm-dd
but in the application for the first entry there is not database value so we create date object and passed the value to web client which gives us timestamp value. The value that will be passed to web client must be in date format soSimpleDateFormat
is not a good choice for meSo from this post ı understand the difference of
java.sql.date
and java.util.date and then create first object aswhich gives
yyyy-mm-dd
value fortoString
method.java.time
BalusC的回答是正确的:您无法从定义为保存的类对象中消除时间日期加上一天中的时间。
此外,您正在使用麻烦的旧类(
java.util.Date
和java.sql.Date
),它们现已过时,被 java.time< /em> 类。相反,请使用仅日期类作为仅日期值。
LocalDate
类表示仅日期值,没有时间和时区。 java.sql.Date 假装执行相同的操作,但实际上由于从 java.util 继承的设计决策非常糟糕,因此确实携带了一天中的时间。日期。避免使用java.sql.Date
,而仅使用java.time.LocalDate
。显然,您是从 java.util.Date 对象开始的。它代表 UTC 时间线上的一个点,分辨率以毫秒为单位。因此,使用它来确定日期需要时区。
LocalDate
类表示仅日期值,没有时间和时区。时区对于确定日期至关重要。对于任何特定时刻,全球各地的日期都会因地区而异。例如,在法国巴黎午夜过后几分钟,又是新的一天“昨天”在魁北克蒙特利尔。
如果未指定时区,JVM 会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好明确指定您想要/预期的时区作为参数。
以
大陆/地区
格式指定正确的时区名称 ,例如美国/蒙特利尔
、非洲/卡萨布兰卡
,或太平洋/奥克兰
。切勿使用 3-4 个字母的缩写,例如EST
或IST
,因为它们不是真正的时区,不是标准化的,甚至不是唯一的( !)。如果您想使用 JVM 当前的默认时区,请询问它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为默认值可能会在运行时的任何时刻被 JVM 内任何应用程序的任何线程中的任何代码更改。
要从
java.util.Date
获取仅日期值,请首先转换为其 java.time 替代品,即时
。要来回转换,请调用添加到旧类中的新方法。根据定义,该值采用 UTC 格式。应用您所需的时区 (
ZoneId
) 来生成ZonedDateTime
。最后,从
ZonedDateTime
中提取所需的LocalDate
对象。从 JDBC 4.2 及更高版本开始,您可以直接与数据库交换 java.time 类。因此不需要使用
java.sql
类,例如java.sql.Date
和java.sql.Timestamp
。检索。
关于 java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如
java.util.Date
,日历
, & ;SimpleDateFormat
。Joda-Time 项目,现已在 维护模式,建议迁移到java.time 类。
要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310。
您可以直接与数据库交换java.time对象。使用符合 JDBC 驱动程序 /jeps/170" rel="nofollow noreferrer">JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。
从哪里获取 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time 。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如
间隔
,YearWeek
,YearQuarter
和 更多。java.time
The Answer by BalusC is correct: You cannot eliminate a time-of-day from a class object defined to hold a date plus a time-of-day.
Also, you are using troublesome old classes (
java.util.Date
andjava.sql.Date
) that are now obsolete, supplanted by the java.time classes.Instead, use a date-only class for a date-only value. The
LocalDate
class represents a date-only value without time-of-day and without time zone. Thejava.sql.Date
pretends to do the same, but actually does carry a time of day due to very poor design decision of inheriting fromjava.util.Date
. Avoidjava.sql.Date
, and use onlyjava.time.LocalDate
instead.You are starting with a
java.util.Date
object apparently. That represents a point on the timeline in UTC with a resolution in milliseconds. So using that to determine a date requires a time zone. TheLocalDate
class represents a date-only value without time-of-day and without time zone.A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of
continent/region
, such asAmerica/Montreal
,Africa/Casablanca
, orPacific/Auckland
. Never use the 3-4 letter abbreviation such asEST
orIST
as they are not true time zones, not standardized, and not even unique(!).If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
To get a date-only value from your
java.util.Date
, first convert to its java.time replacement,Instant
. To convert back and forth, call new methods added to the old classes.That value is in UTC by definition. Apply your desired time zone (
ZoneId
) to generate aZonedDateTime
.Finally, extract your desired
LocalDate
object fromZonedDateTime
.As of JDBC 4.2 and later, you can directly exchange java.time classes with your database. So no need to use the the
java.sql
classes such asjava.sql.Date
andjava.sql.Timestamp
.Retrieval.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project 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.