【问题标题】:Exact string to date and keep original format [duplicate]迄今为止的确切字符串并保持原始格式[重复]
【发布时间】:2021-08-22 13:34:51
【问题描述】:

我在这方面四处寻找帮助,但同样,这只是我无法为我的具体问题找到合适答案的事情之一。

这里有 2 篇非常详细(而且很有帮助) 我看过的 SO 帖子:

Change date format in a Java string

Java string to date conversion

这就是我所拥有的:

//Date Formatter
SimpleDateFormat dateFormatter1 = new SimpleDateFormat("yyyy-MM-dd", new Locale("EN"));
SimpleDateFormat dateFormatter2 = new SimpleDateFormat("dd MMMM yyyy", new Locale("EN"));

//Convert to Date
Date dateToParse = dateFormatter1.parse("2024-01-01");

//Format OUTPUT date
String dateAsString = dateFormatter1.format(dateToParse);

System.out.println(dateAsString); //01 January 2024

//Convert OUTPUT date from STRING to DATE
Date dateToReturn = dateFormatter1.parse(dateAsString);

System.out.println(dateToReturn.toString()); //Mon Jan 01 00:00:00 SAST 2024

注意:

我同时使用了DateFormatterSimpleDateFormatter,但得到了相同的输出。

输出非常不同,我想要实现的是让我的String 以完全相同的格式创建为Date 对象。

我觉得我错过了什么,但我就是不知道是什么。

  1. 我提供的代码是来自一个更大函数的 sn-p,它返回类型 Date
  2. 该函数不是我自己创建的,我是从其他人停止的地方开始的

【问题讨论】:

  • 这并不重要,但你不应该使用 SimpleDateFormat
  • @OneCricketeer 同意,我实际上将其更改为DateFormatter。我尝试了两种方法,但以相同的结果结束。 :)
  • 日期实例没有格式。 LocalDate 或 ZonedDate 也没有。当您将日期输出为字符串时,日期具有格式。
  • 我建议你不要使用DateFormatSimpleDateFormatDate。这些类的设计很差而且已经过时了,尤其是前两个是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateDateTimeFormatter
  • @OneCricketeer 感谢您提供以下反馈和答案。我将考虑将函数更改为使用LocalDateDateTimeFormatter。 :)

标签: java simpledateformat


【解决方案1】:

每当您在 Date 上调用 .toString() 方法时,都不会考虑 DateFormatter。您获得的日期格式只是Date 类的默认toString 实现问题。

要在打印时使用格式化程序,请尝试以下操作(而不是 sn-p 中的最后一行): System.out.println(dateFormatter1.format(dateToReturn));

【讨论】:

  • 谢谢你的回答,绝对有道理:)。我想我可能遗漏了我的帖子的一个重要部分,我不认为包括在内,但现在会更新它。问题不是我真的想把它打印出来,它实际上是一个返回 Date 类型的函数的代码 sn-p,在我调用该函数的地方,我不能“重用”日期格式,因为它已更改为 ISO8601,如前所述上面的 OneCricketeer
  • 假设您可以更改方法以返回 LocalDate,它也没有任何固有格式,那么在从方法?
  • @OleV.V.是的,谢谢。我希望这样做(将其更改为LocalDate)。我发表这篇文章的原因实际上是因为在返回 Date 之后将其格式化为 String 并且没有得到正确的值。但如前所述,我使用的是过时且有问题的DateFormatters :)
【解决方案2】:

Date.toString() returns always returns a string in the format dow mon dd hh:mm:ss zzz yyyy.

您需要重用格式化程序的格式化方法来获取您期望的初始字符串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多