SimpleDateFormat解析错误的日期 [英] SimpleDateFormat parsing wrong date

查看:57
本文介绍了SimpleDateFormat解析错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我试图比较3个日期,为此,我向一个函数传递了一个日期和两个字符串.而且我正在使用简单的日期格式来制作3个相同格式的日期,以便可以对其进行比较.但是对于两个字符串值,我在解析它时得到了错误的日期.谁能帮忙吗?

Here I am trying to compare 3 dates, for that, I have passed a date and two string to a function. And I am using simple date format to make 3 dates of the same format so that I can compare them. But for the two string value, I am getting the wrong date when I parse it. Can anyone please help?

Private boolean compareDate(Date cdate, String fdate, String date) {
    //cdate = 2020-03-25 09:05:47
    //fdate = 03/10/2020
    //tdate = 03/25/2020

    SimpleDateFormat sd= new SimpleDateFormat("dd/MM/yyyy");
    String s=sd.format(cdate);
    Date d1=sd.parse(s);
    Date d2=sd.parse(fdate);
    Date d3=sd.parse(tdate);
}

解析后得到的值是:

D1 = wed Mar 25 00:00:00 IST 2020
D2 = sat Oct 03 00:00:00 IST 2020 //wrong date fdate was 03/10/2020
D3 = Mon Jan 03 00:00:00 IST2020 //wrong date  tdate was 03/25/2020

谁能告诉我我哪里出了错?由于这个问题,我无法正确比较它们.

Can anyone tell where did I go wrong? And due to this issue, I am not able to properly compare them.

推荐答案

tl; dr

myJavaUtilDate 
.toInstant()
.atZone
(
    ZoneId.of( "Asia/Kolkata" ) 
)
.toLocalDate()
.isEqual
(
    LocalDate
    .parse
    (
        "03/10/2020" ,                              // Do you mean March 10th, or October 3rd? 
        DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Or "MM/dd/uuuu".
    )
)

智能对象,而不是哑字符串

您说:

制作3个相同格式的日期,以便我进行比较

make 3 dates of the same format so that I can compare them

将对象与比较方法一起使用,而不是比较字符串的文本.

Use objects with comparison methods, rather than comparing text of strings.

我们有一个内置于Java中的日期类: LocalDate .

We have a class for dates built into Java: LocalDate.

您正在使用 Date ,它是与最早的Java版本捆绑在一起的可怕的日期时间类之一.这些类现在已经过时了,几年前通过定义 java.time 类的JSR 310取代了.

You are using Date which is one of the terrible date-time classes bundled with the earliest versions of Java. These classes are now obsolete, supplanted years ago with the adoption of JSR 310 that defines the java.time classes.

我已经过了日期

遇到 java.util.Date 对象时,请立即转换为其现代替代品 java.time.Instant .使用新的转换方法 toInstant 已添加到旧类中.

When encountering a java.util.Date object, immediately convert to its modern replacement, java.time.Instant. Use the new conversion method toInstant added to the old class.

Instant instant = myJavaUtilDate.toInstant() ;

java.util.Date java.time.Instant 均表示UTC中的时刻.这就是您要如何以UTC来感知日期,而该日期与本初子午线的偏移量为零小时-分钟-秒吗?请记住,在任何给定的时刻,日期都会在全球范围内变化.在日本东京可能是明天",而在美国俄亥俄州托莱多仍然是昨天".

Both java.util.Date and java.time.Instant represent a moment in UTC. Is that how you want to perceive the date, in UTC with an offset of zero hours-minutes-seconds from the prime meridian? Keep in mind that for any given moment the date varies around the globe by zone. A moment may be "tomorrow" in Tokyo Japan while still "yesterday" in Toledo Ohio US.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

提取日期.

LocalDate ld = odt.toLocalDate() ;  // Extract the date only, omitting the time-of-day and the offset-from-UTC.

还是您想在特定区域中看到该日期?

Or did you want to perceive that date in a particular zone?

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
LocalDate ld = zdt.toLocalDate() ;  // Extract the date only, omitting the time-of-day and the zone.

和一个函数的两个字符串

and two string to a function

定义一种格式设置以匹配您的输入.

Define a formatting pattern to match your inputs.

String input = "03/10/2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;  // Throws `DateTimeParseException` if input is faulty.

现在使用方法

java.util.Date::toString 撒谎

您问:

java.util.Date::toString tells a lie

You asked:

D2 =星期六十月03 00:00:00 IST 2020//日期错误的日期是03/10/2020

谁能告诉我我出了什么问题?

Can anyone tell where did I go wrong?

您的主要问题是您的格式化模式未定义为符合您的意图.这在克里斯(Chris)的答案

Your main problem is that your formatting pattern is not defined to match your intention. This is correctly identified in the Answer by Chris and the Answer by Arvind Kumar Avinash.

此外,您还有另一个问题. java.util.Date 的许多问题之一是,它的 toString 方法在生成文本以表示文本内容时,会即时应用JVM当前的默认时区.目的.这产生了将该区域存储在对象中的错觉.调整到时区后,如果您感觉到 Date 对象的UTC值,则日期可能会与UTC中显示的日期有所不同.上面已经讨论过了.

In addition, you have another issue. Among the many problems with java.util.Date is that its toString method on-the-fly applies the JVM’s current default time zone while generating text to represent the content of the object. This creates the illusion of that zone being stored within the object. When perceiving your Date object’s UTC value after adjusting to a time zone, the date may differ from the date as seen in UTC. This was discussed above.

➥切勿使用 java.util.Date .

➥ Never use java.util.Date.

旧版日期时间类,例如 SimpleDateFormat .

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.

要了解更多信息,请参见 Oracle教程.并在Stack Overflow中搜索许多示例和说明.规范为 JSR 310 .

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Joda-Time 项目,现在位于<一个href ="https://en.wikipedia.org/wiki/Maintenance_mode" rel ="nofollow noreferrer">维护模式,建议迁移到您可以直接与数据库交换 java.time 对象.使用符合 JDBC驱动程序/jeps/170"rel =" nofollow noreferrer> JDBC 4.2 或更高版本.不需要字符串,不需要 java.sql.* 类.

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.

在哪里获取java.time类?

Where to obtain the java.time classes?

  • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Later versions of Android bundle implementations of the java.time classes.
  • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

这篇关于SimpleDateFormat解析错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆