【问题标题】:how to change the format of Calendar object [duplicate]如何更改日历对象的格式[重复]
【发布时间】:2018-05-11 07:03:58
【问题描述】:

我有一个字符串,例如IST 2018 年 5 月 10 日星期四 15:48:23。如何将此字符串转换为日历对象的形式,格式为 2018-05-10 15:48:23.84。

【问题讨论】:

  • 您使用DateTimeFormatterString 解析为LocalDateTime 对象,然后使用另一个DateTimeFormatter 将该值格式化为另一个String
  • @MadProgrammer 感谢您的回复。我实际上希望最终结果是具有所需格式的日历对象,而不是字符串。
  • @ABHISHEKSRIVASTAVA 1. Calendar 已过期,您不应再使用它; 2. Calendar(和Date 和所有其他“日期/时间”类)只是代表某个时间点的值的容器,它们自己没有任何“格式化”功能
  • 同意你应该完全避免Calendar并使用java.time。也就是说,Calendar 不能包含格式。您想拥有的任何格式,都只能在String 中拥有。这也是模型/业务数据与向用户呈现数据之间的良好分离。

标签: java calendar


【解决方案1】:

首先查看DateTimeFormatterParsing and Formatting,了解有关如何在Java 8+ 中解析和格式化日期/时间值的更多详细信息

根据您的示例,类似...

String inValue = "Thu May 10 15:48:23 IST 2018";
DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(inValue, inFormatter);
DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS", Locale.ENGLISH);
String outValue = outFormatter.format(ldt);
System.out.println(outValue);

将打印2018-05-10 15:48:23.00

感谢您的回复。我实际上希望最终结果是具有所需格式的日历对象,而不是字符串。

  1. Calendar 已被有效弃用,你不应该再使用它了。即使您没有使用 Java 8+,也应该使用 ThreeTen Backport API
  2. Calendar(和Date 和所有其他“日期/时间”类)只是代表某个时间点的值的容器,它们自己没有任何类型的“格式化”功能。这就是 API 具有格式化类的原因。将日期/时间值保留为适当的类,直到您需要显示它们,此时,您应该将值格式化为 String

【讨论】:

    猜你喜欢
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2020-07-29
    • 2020-10-28
    • 1970-01-01
    • 2017-11-14
    相关资源
    最近更新 更多