I'm using ThreeTenABP for converting date time for Android.
My question is how can I change a java.util.Date
to an ISO String (format is 2018-05-24T02:33:10.062Z
) by ThreeTenABP?
Asked
Active
Viewed 840 times
3 Answers
4
A ThreetenABP-solution can look like this:
java.util.Date d = ...;
org.threeten.bp.Instant instant = org.threeten.bp.DateTimeUtils.toInstant(d);
String iso = instant.toString();
If you wish more control over formatting then you can convert the instant to a ZonedDateTime
(or better to an OffsetDateTime) and use a dedicated DateTimeFormatter
.

Meno Hochschild
- 42,708
- 7
- 104
- 126
-
You save my day too. That's more relevant answer for my question – amlwin Jun 04 '18 at 03:43
-
@OleV.V. I agree that using a fixed offset and hence the type `OffsetDateTime` is here the natural choice. Have adjusted the answer accordingly. – Meno Hochschild Jun 04 '18 at 09:53
1
I do not know about android, but if java.text.SimpleDateFormat
is available you could do:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(new Date())

Kimses
- 707
- 7
- 17
-
Currently ur answer suitable for me. But I also need with `threetenabp` – amlwin Jun 01 '18 at 09:35
-
1Escaping the pattern letter "Z" is a heavy mistake resulting in wrong data. But using the pattern letter "X" is a good alternative. – Meno Hochschild Jun 01 '18 at 10:20
-
There is a way through to getting the string with correct time *and* the `Z` with `SimpleDateFormat` (at least if your Android API level is high enough), but it’s not straightforward. Since `SimpleDateFormat` is both outdated and notoriously troublesome, I’d rather not bother, and would use [the good answer by Meno Hochschild](https://stackoverflow.com/a/50641263/5772882) instead. – Ole V.V. Jun 01 '18 at 11:19
-
yes, of course it is better to set a timezone on the format. next time i'll be more cautious when posting answers. – Kimses Jun 01 '18 at 14:03
0
Expression:
new Date().toInstant().toString()
results in
2019-12-31T06:32:37.997Z

Алексей Виноградов
- 1,005
- 13
- 10