5

I need the current system date and time in 2022-10-03T19:45:47.844Z format in a java class.

I tried using the zoneddatetime and simple date format but couldn't get the write syntax or code from online. I'm beginner in Java, any help is appreciated. Thanks.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    `Instant.now().toString()` (yes, if you accept not having control over the number of decimals, it really is this simple). Leave out `.toString()` if you do not require a `String`. – Ole V.V. Nov 08 '22 at 06:48
  • 1
    @OleV.V. Neither [that Question](https://stackoverflow.com/q/56933100/642706) nor [that Question](https://stackoverflow.com/q/64872001/642706) is a direct original of this one. Both are convoluted, neither directly asks for today's date in ISO 8601 format, and both are Android-specific. I expected an original existing Question to mark this Question as a duplicate, but I could not find one. Thus my Answer. – Basil Bourque Nov 09 '22 at 00:46
  • Do you know for a fact that you need exactly three decimals of fraction of second (as in `.844`)? Asking because your format is [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) and that standard doesn’t put a limit on the number of decimals. – Ole V.V. Nov 09 '22 at 03:11
  • Does this answer your question? [How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?](https://stackoverflow.com/questions/1459656/how-to-get-the-current-time-in-yyyy-mm-dd-hhmisec-millisecond-format-in-java) – Karl Knechtel Sep 02 '23 at 03:25

3 Answers3

3

tl;dr

Instant.now().toString()

See this code run at Ideone.com.

2022-11-08T07:18:21.482293Z

Instant.now().toString()

As commented by Ole V.V., you can capture the current moment as seen with an offset of zero hours-minutes-seconds from UTC by using the java.time.Instant class.

Instant instant = Instant.now() ;

ISO 8601

You can generate a string in standard ISO 8601 format, your desired format. by calling Instant#toString().

String output = instant.toString() ;

Of course we can combine these:

Instant.now().toString()  

Resolution

An Instant represents a moment in UTC with a resolution as fine as nanoseconds.

Note that Instant#toString uses a formatter that formats the fractional seconds in groups of three digits, up to nine digits for nanoseconds. Any finer group of all zeros is suppressed. So if your Instant has only milliseconds with zero microseconds/nanoseconds, you get three digits. If micros without nanos, six digits. If nanos, nine digits.

You will likely capture the current moment with:

  • Milliseconds (3 digits in fractional second) in Java 8.
  • Microseconds (6 digits) in Java 9 and later, due to a fresh implementation of the Clock class in the OpenJDK project’s codebase.

Common computer hardware clocks are not accurate in nanoseconds. So a Instant can represent a value with nanoseconds, but you'll not likely see the current moment captured with that precision.

If you want only milliseconds, truncate. Specify your desired granularity by way of ChronoUnit enum, and implementation of TemporalUnit.

Instant.now().truncatedTo( ChronoUnit.MILLIS ).toString()

But remember, if you happened to have a fractional second of zero, no fractional second digits at all would appear in the resulting String object.

Z

The Z on the end of your desired format means an offset of zero. Pronounced “Zulu”. Comes from aviation/military history. Standardized in ISO 8601.

Avoid legacy date-time classes

You said:

I tried using the zoneddatetime and simple date format

The java.time.ZonedDateTime class is for representing a moment as seen in a particular time zone. Your desired format has no time zone, only an offset of zero. So ZonedDateTime is not appropriate here. Use Instant instead, or use OffsetDateTime if you need more flexibility such as other formatters.

Definitions:

  • An offset is merely a number of hours-minutes-seconds ahead or behind the temporal prime meridian of UTC.
  • A time zone is much more. A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region as decided by their politicians.

Never use the terribly flawed classes of SimpleDateFormat, Date, Calendar, etc. These are now legacy since Java 8+, supplanted by the modern java.time classes defined in JSR 310.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)

Shakirov Ramil
  • 1,381
  • 9
  • 13
  • Not completely correct, though on the right track. Expected output: `2022-11-08T08:16:24.715Z` Observed output in my time zone: `2022-11-08T09:16:24.715128761`. The time is 1 hour off corresponding to my UTC offset, and the trailing `Z` is missing. It does not matter that there are more decimals since according to the ISO 8601 standard the number of decimals is free. – Ole V.V. Nov 08 '22 at 08:19
1

What you have is a fully specified timestamp in standard ISO 8601 format. While java.util.Date and friends make this difficult, you can include joda in your classpath and use the following incantation to manipulate it:

System.out.println(ISODateTimeFormat.dateTime().print(DateTime.now());

Good luck!

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
hd1
  • 33,938
  • 5
  • 80
  • 91
  • 2
    The [*Joda-Time*](https://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode). Its successor is the *java.time* classes built into Java 8, defined by JSR 310. Both Joda-Time and JSR 310 are lead by the same man, Stephen Colebourne. – Basil Bourque Nov 08 '22 at 06:59