0

I want this result on date time: 2008-10-31T15:07:38.6875000-05:00, please help me how i get this result?

I am using following code but unable to get required response.

TimeZone tzone = TimeZone.getTimeZone("UTC");
DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); 
String nowAsISO = dateformat.format(new Date());
M.A.Bell
  • 398
  • 1
  • 16
Muhammad Kazim
  • 611
  • 2
  • 11
  • 26
  • yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ – LenglBoy Nov 06 '17 at 10:10
  • 1
    For starters, if you want 4 or 7 decimals on your seconds, you cannot use the `Date` class, it has only millisecond precision (3 decimals). You’re far from lost, though: it’s so much better of an opportunity to start using [the modern Java date and time API known as JSR-310 or `java.time`](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 06 '17 at 12:42
  • 1
    Use the modern Java date and time API. The `toString` methods of its classes produce ISO-8601 format natively: `OffsetDateTime.now(ZoneOffset.ofHours(-5)).toString()`. – Ole V.V. Nov 06 '17 at 12:47

1 Answers1

-1

You are quite right:

Your format expression is missing seconds :ss, millisecond .SSS (many S for how many digit you want) and the Z timezone tag without '

Using single quote ' in the expression will exclude everything included in them from parsing, ergo you will have it printed like a string.

TimeZone tzone = TimeZone.getTimeZone("UTC");
DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ"); 
String nowAsISO = dateformat.format(new Date());

You can see every possible pattern here

Marcx
  • 6,806
  • 5
  • 46
  • 69
  • 1
    Wrong answer. We can specify only 3 pattern symbols "SSS" because the old `SimpleDateFormat`-API supports millisecond precision, not more. And the timezone should be set, too, but the code for that is also missing. – Meno Hochschild Nov 06 '17 at 12:38
  • On my computer I got `2017-11-06T14:14:35.0000511+0100`. The decimals are wrong, they should at least be `.5110000`. And the OP asked for a colon in the offset (`-05:00`). Also you are not using your variable `tzone` for anything. – Ole V.V. Nov 06 '17 at 13:16
  • 1
    **Incorrect Answer**, as others commented about these classes supporting only milliseconds while the Question requires a resolution finer than microseconds. And this Answer uses troublesome old date-time classes that are now legacy, supplanted by the java.time classes. – Basil Bourque Nov 06 '17 at 15:16