无法将字符串 dd/MM/yyyy 转换为 java 中的日期 dd/MM/yyyy

Not able to convert string dd/MM/yyyy to Date dd/MM/yyyy in java

我有一个格式为 dd/MM/yyyy 的输入字符串,我需要将其转换为日期 dd/MM/yyyy

我的做法是:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String date = formatter.format(formatter.parse("22/09/2016"));
Date convertedDate = formatter.parse(date);

我期待 22/09/2016 作为日期对象,但返回的格式与预期不同。 O/P=>Mon Sep 12 00:00:00 IST 2016

知道我哪里出错了吗?提前致谢!

 try {
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            Date d = formatter.parse("22/09/2016");
            System.out.println(d.toString());
            String e = formatter.format(d);
            System.out.println(e);
        } catch (ParseException ex) {
            Logger.getLogger(Json.class.getName()).log(Level.SEVERE, null, ex);
        }

您似乎假设 java.util.Date "knows" 一种格式。它没有。这不是它的状态的一部分——它 只是 自 Unix 纪元以来的毫秒数。 (也没有时区 - 您看到的 IST 是您当地的时区;这只是 Date.toString() 所做的一部分。)

基本上,Date 只是一个瞬间 - 当您需要特定格式的值时,就是您使用 SimpleDateFormat.

的时候

(或者更好,使用 java.time.*...)

将它想象成一个数字 - 无论您将它用二进制表示为 10000、十进制表示为 16 还是十六进制表示为 0x10,数字 16 都是相同的数字。 int 值没有任何 "I'm a binary integer" 或 "I'm a hex integer" 的概念 - 只有当您将其转换为字符串时才需要关心格式。 date/time 类型也是如此。

A Date,打印时会调用对象的toString方法。然后它将选择它想要的任何格式。

尝试

System.out.println(formatter.format(convertedDate));

或者 - 显然

System.out.println(date);

tl;博士

LocalDate.parse( "22/09/2016" , DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
         .format( DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )

问题

  • 您将日期时间对象与表示日期时间值的字符串混为一谈。日期时间对象可以解析字符串,并可以生成字符串,但日期时间对象始终与字符串分开且不同。 字符串有格式;日期时间对象 not.
  • 您使用的是麻烦的旧日期时间 classes,现在已被 java.time classes 取代。
  • 您正在尝试将仅限日期的值放入日期时间对象(方钉、圆孔)。
  • 您被设计不当的 toString 方法欺骗了,该方法默默地将时区应用于没有时区(UTC)的内部值。

务必阅读

java.time

使用新的 java.time classes,特别是 LocalDateLocalDate class 表示没有时间和时区的仅日期值。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
LocalDate ld = LocalDate.parse( "22/09/2016" , f );

通过调用 toString.

生成一个字符串以标准 ISO 8601 格式表示该值
String output = ld.toString(); // 2016-09-22

通过应用格式化程序生成所需格式的字符串。

String output = ld.format( f );

关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

Joda-Time project, now in maintenance mode,建议迁移到java.time。

要了解更多信息,请参阅 Oracle Tutorial。并在 Stack Overflow 中搜索许多示例和解释。

许多 java.time 功能被反向移植到 ThreeTen-Backport and further adapted to Android in ThreeTenABP (see 中的 Java 6 和 7。

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.