如何更改日历对象的格式 [英] how to change the format of Calendar object

查看:117
本文介绍了如何更改日历对象的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string e.g. Thu May 10 15:48:23 IST 2018. How to convert this string in the form of Calendar object with format 2018-05-10 15:48:23.84.

推荐答案

首先查看 DateTimeFormatter 解析和格式化以获取有关如何在Java 8+中解析和格式化日期/时间值的更多详细信息

Start by using having a look at DateTimeFormatter and Parsing and Formatting for more details about how to parse and format date/time values in Java 8+

基于在您的示例中,类似...

Based on your examples, something like...

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


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

Thank you for your response. I actually want the end result as Calendar Object with required format, not a string.




  1. 日历已被弃用,您不应该再使用它。即使您没有使用Java 8+,也应该使用 ThreeTen Backport API

  2. 日历(以及 Date 和所有其他日期/时间类)是只是具有表示某个时间点的值的容器,它们本身没有任何格式化功能。这就是API具有格式设置类的原因。保持将日期/时间值表示为适当的类,直到需要显示它们为止,此时,应将值格式化为 String

  1. Calendar is effectively deprecated, you shouldn't be using it anymore. Even if you're not using Java 8+, you should be using the ThreeTen Backport API
  2. Calendar (and Date and all other "date/time" class) are just containers of a value representing some point in time, they do not have any kind of "formatting" capabilities of their own. This is why the API has formatting classes. Keep you date/time values represented as appropriate classes until you need to display them, at that point, you should format the value to a String

这篇关于如何更改日历对象的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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