Date.toString() - sql 与 util 日期

发布于 2024-12-17 18:33:07 字数 1377 浏览 0 评论 0 原文

我需要从 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 的格式不同。我缺少一些东西。请帮忙。

更新:

在我的应用程序中,我有两种不同的方法来获取dbDateEXPIRY_DATE 列是 DATE 类型。

第一个查询使用 dbDate = (java.util.Date) rs.getDate("EXPIRY_DATE");。

对于此 dbDateSystem.out.println("date " + dbDate); 给出 date 2011-12-03

第二个查询使用 dbDate = rs.getTimestamp("EXPIRY_DATE");

对于此 dbDateSystem.out.println("date " + dbDate); 给出日期 2011-12-03 23:59:59.0

这是我的问题。由于我认为 toString() 出现了问题,因此我没有提及完整的问题。

解决方案:

我没有选择避免使用java.sql.Date,因为我的应用程序方法有多种用途。 我尝试了下面的方法并工作了,

dbDate = new java.sql.Date(dbDate.getTime());

I need to remove time from a Date Object. Here is my try,

Code:

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)));

Output:

date 2011-12-03 23:59:59.0
formatter.format(dbDate) 2011-12-03
final Sat Dec 03 00:00:00 IST 2011

I want to the final date to display in 2011-12-03. But after conversion toString() of that Date is in different format. I am missing something. Please help.

Update:

In my application, I have two different methods to get dbDate. EXPIRY_DATE column is type of DATE.

First query uses dbDate = (java.util.Date) rs.getDate("EXPIRY_DATE");.

For this dbDate, System.out.println("date " + dbDate); gives date 2011-12-03

Second query uses dbDate = rs.getTimestamp("EXPIRY_DATE");

For this dbDate, System.out.println("date " + dbDate); gives date 2011-12-03 23:59:59.0.

This is my problem. As I thought toString() was giving problem, I didn't mention the full problem.

Solution:

I did not have choices to avoid java.sql.Date as my application methods have multiple usages.
I tried the below and worked,

dbDate = new java.sql.Date(dbDate.getTime());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

暮倦 2024-12-24 18:33:07

我需要从日期对象中删除时间

你不能。 java.util.Date 对象包含日期和时间。它的 toString() 也在 固定格式。如果您想在没有时间的情况下将其表示给人类,那么您需要像您已经做的那样将其转换为 String 。或者,如果您打算将其存储在没有时间的数据库中(如变量名称 dbDate 中的 db 部分所示),那么您需要将其转换为 java.sql.Date

preparedStatement.setDate(1, new java.sql.Date(dbDate.getTime()));
// ...

更新 根据您的更新,ResultSet#getDate() 返回 java.sql.Date 的实例,而不是 java.util .Date (但它是 java.util.Date 的子类,这就是为什么不必要的转换起作用的原因;请注意,转换与转换不同,真正的转换将是 <代码>新java.util.Date(dbDate.getTime()))。正如您可以在 中阅读的java.sql.DatetoString()方法的javadoc,它确实是yyyy-MM-dd格式。

因此,您的具体问题是您将 java.sql.Datejava.util.Date 混淆了,并且您误解了 java 的内部工作原理.util.Date 并被 toString() 方法误导。一切都按预期进行。

相关:

I need to remove time from a Date Object

You can't. The java.util.Date object contains both the date and time. Its toString() is also in a fixed format. If you want to represent it without time to humans, then you need to convert it to a String like as you already did. Or, if you intend to store it in the DB without the time (as the db part in the variable name dbDate suggests), then you need to convert it to java.sql.Date.

preparedStatement.setDate(1, new java.sql.Date(dbDate.getTime()));
// ...

Update as per your update, the ResultSet#getDate() returns an instance of java.sql.Date, not java.util.Date (but it is a subclass of java.util.Date, that's why the unnecessary cast worked; please note that casting is not the same as converting, a real conversion would be new java.util.Date(dbDate.getTime())). As you can read in the javadoc of the toString() method of java.sql.Date, it's indeed in yyyy-MM-dd format.

So, your concrete problem is that you're confusing java.sql.Date with java.util.Date and that you're misgrasping the internal workings of java.util.Date and been mislead by the toString() method. Everything is working as intented.

Related:

怪我入戏太深 2024-12-24 18:33:07

如果您想要删除 Date 对象的时间部分:

如果您只想获取 String 表示形式,而没有 Date 对象的时间部分:

  • 您必须使用 SimpleDateFormat.format() 。您不能让 Date.toString() 返回不同的值,它将始终使用该模式。看看它的 源代码

If what you want to do is remove the time part of the Date object:

If you only want to obtain a String representation without the time part of the Date object:

  • You've got to use SimpleDateFormat.format(). You can't make Date.toString() return a different value, it will always use that pattern. Look at its source code.
云归处 2024-12-24 18:33:07

当您最后一次调用 formatter.parse() 时,您将返回一个 Date 对象;然后,串联对 Date.toString() 进行隐式调用:此调用返回的格式是 JVM 中设置的区域设置的默认格式。
您必须了解的是 Date 对象不知道字符串表示形式,在内部它只是 inte 的聚合

When you last call formatter.parse() you get back a Date object; the concatenation then makes an implicit call to Date.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

甜柠檬 2024-12-24 18:33:07

对于那些遇到与我相同问题的人,我也遇到了类似的问题,我写了这个条目:

问题是从数据库获取并传递到 Web 客户端的日期值的格式为 yyyy-mm-dd 但在第一个条目的应用程序中没有数据库值,因此我们创建日期对象并将该值传递给 Web 客户端,该客户端为我们提供时间戳值。将传递给 Web 客户端的值必须采用日期格式,因此 SimpleDateFormat 对我来说不是一个好的选择
因此,从这篇文章中我了解了 java.sql.date 和 java.util.date 的区别,然后创建第一个对象,

Date date = new java.sql.Date(1430454600000L); 

该对象为 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 so SimpleDateFormat is not a good choice for me
So from this post ı understand the difference of java.sql.date and java.util.date and then create first object as

Date date = new java.sql.Date(1430454600000L); 

which gives yyyy-mm-dd value for toString method.

扛起拖把扫天下 2024-12-24 18:33:07

java.time

BalusC的回答是正确的:您无法从定义为保存的类对象中消除时间日期加上一天中的时间。

此外,您正在使用麻烦的旧类(java.util.Datejava.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 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的( !)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

如果您想使用 JVM 当前的默认时区,请询问它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为默认值可能会在运行时的任何时刻被 JVM 内任何应用程序的任何线程中的任何代码更改。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

要从 java.util.Date 获取仅日期值,请首先转换为其 java.time 替代品,即时。要来回转换,请调用添加到旧类中的新方法。

Instant instant = myJavaUtilDate.toInstant() ;

根据定义,该值采用 UTC 格式。应用您所需的时区 (ZoneId) 来生成 ZonedDateTime

ZonedDateTime zdt = instant.atZone( z ) ;

最后,从 ZonedDateTime 中提取所需的 LocalDate 对象。

LocalDate ld = zdt.toLocalDate() ;

从 JDBC 4.2 及更高版本开始,您可以直接与数据库交换 java.time 类。因此不需要使用java.sql类,例如java.sql.Datejava.sql.Timestamp

myPreparedStatement.setObject( … , ld ) ;

检索。

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

关于 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 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeekYearQuarter更多

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 and java.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. The java.sql.Date pretends to do the same, but actually does carry a time of day due to very poor design decision of inheriting from java.util.Date. Avoid java.sql.Date, and use only java.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. The LocalDate 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 as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

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.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

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.

Instant instant = myJavaUtilDate.toInstant() ;

That value is in UTC by definition. Apply your desired time zone (ZoneId) to generate a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z ) ;

Finally, extract your desired LocalDate object from ZonedDateTime.

LocalDate ld = zdt.toLocalDate() ;

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 as java.sql.Date and java.sql.Timestamp.

myPreparedStatement.setObject( … , ld ) ;

Retrieval.

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文