无法在java中将字符串dd / MM / yyyy转换为Date dd / MM / yyyy

问题描述 投票:0回答:4

我有一个格式为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

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

java date-format simpledateformat
4个回答
3
投票

tl;dr

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

Problems

  • 您将日期时间对象与表示日期时间值的字符串混淆。日期时间对象可以解析字符串,并且可以生成字符串,但是日期时间对象始终是独立的并且与字符串不同。字符串有格式;日期时间对象没有。
  • 您正在使用现在由java.time类取代的麻烦的旧日期时间类。
  • 您试图将仅日期值放入日期时间对象(方形挂钩,圆孔)。
  • 您被设计不佳的toString方法欺骗,该方法将时区静默应用于没有时区的内部值(UTC)。

一定要阅读the correct Answer by Jon Skeet

java.time

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

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

通过调用ISO 8601生成一个String,以标准toString格式表示该值。

String output = ld.toString(); // 2016-09-22

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

String output = ld.format( f );

About java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧日期时间类,如java.util.Date.Calendarjava.text.SimpleDateFormat

Joda-Time项目,现在在maintenance mode,建议迁移到java.time。

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

许多java.time功能在ThreeTen-Backport中被反向移植到Java 6和7,并进一步适应Android中的ThreeTenABP(参见How to use…)。

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。你可能会在这里找到一些有用的类,如IntervalYearWeekYearQuartermore


6
投票

你好像假设java.util.Date“知道”一种格式。它没有。这不是它的状态的一部分 - 它只是自Unix时代以来的毫秒数。 (也没有时区 - 你看到IST是你当地的时区;这只是Date.toString()所做的一部分。)

基本上,Date只是瞬间 - 当你想要一个特定的格式化值时,那就是当你使用SimpleDateFormat时。

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

可以把它想象成一个数字 - 数字十六是相同的数字,无论你用二进制表示为10000,十进制表示为16,还是十六进制表示为0x10。 int值没有“我是二进制整数”或“我是十六进制整数”的任何概念 - 只有当您将其转换为需要关注格式的字符串时才会这样。日期/时间类型完全相同。


1
投票
 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);
        }

0
投票

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

尝试

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

或者 - 显然

System.out.println(date);
© www.soinside.com 2019 - 2024. All rights reserved.