Milliseconds not appearing in DateFormat.format output

对着背影说爱祢 提交于 2020-01-06 08:11:14

问题


I want to have a date-time string in the "yyyy-MM-dd'T'HH:mm:ss.SSSZ" format. I wrote the following code snippet:

    Date date=Calendar.getInstance().getTime();
    String currentDateTimeString = (String) android.text.format.DateFormat.
           format("yyyy-MM-dd'T'HH:mm:ss.SSSZ",Calendar.getInstance().getTime());

but I get strings like

"2019-11-08T13:39:33.SSSZ"

also when the format is "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" (with 'Z' escaped).

Patterns are found at https://developer.android.com/reference/java/text/SimpleDateFormat.html#examples

Why milliseconds do not appear?


回答1:


I know little about Android development, but a quick search in the documentation may give you the answer:

https://developer.android.com/reference/android/text/format/DateFormat

The format methods in this class implement a subset of Unicode UTS #35 patterns. The subset currently supported by this class includes the following format characters: acdEHhLKkLMmsyz. Up to API level 17, only adEhkMmszy were supported. Note that this class incorrectly implements k as if it were H for backwards compatibility.

The Unicode UTS #35 says nothing about milliseconds: https://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns

So it seems that formatting milliseconds is not supported.

I would rather use the Java standard classes LocalDateTime and DateTimeFormatter, which do support milliseconds.

https://developer.android.com/reference/java/time/format/DateTimeFormatter.html

[Edited]

After re-reading the question, I think the problem is that you're using DateFormat instead of SimpleDateFormat. The link you've provided does not correspond with the actual class you're using in your code.



来源:https://stackoverflow.com/questions/58767796/milliseconds-not-appearing-in-dateformat-format-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!