0

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?

P5music
  • 3,197
  • 2
  • 32
  • 81
  • @Carlos López Marí As far as I understand the S are placeholders for milliseconds digits, ranging from 000 to 999 but they are written as S characters, as you can see – P5music Nov 08 '19 at 13:51
  • Refering to the root decumentation you are right. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html I think it can be related to the Android implementation, have you tried SimpleDateFormat? – Carlos López Marí Nov 08 '19 at 13:52
  • As an aside consider throwing away the long outmoded and notoriously troublesome `DateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Nov 08 '19 at 16:59

1 Answers1

0

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.

Luis Iñesta
  • 401
  • 3
  • 6
  • The docs reference casting to the `SimpleDateFormat` "If you want even more control over the format or parsing, (or want to give your users more control), you can try casting the `DateFormat` you get from the factory methods to a `SimpleDateFormat`" – Michael McKay Nov 08 '19 at 14:26