tl;dr
Convert from troubled legacy class to modern class, then generate text in standard ISO 8601 format.
myTimestamp.toInstant().toString()
Or capture the current moment in UTC.
Instant.now().toString()
Details
A java.sql.Timestamp
object does not have have a “format”. The Timestamp
class represents a moment, not text.
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
java.time.Instant
If you have a Timestamp
object in hand, convert to its replacement, java.time.Instant
. Look to new conversion methods added to the old classes.
Instant instant = myTimestamp.toInstant() ;
Capture the current moment as seen in UTC, with an offset from UTC of zero hours-minutes-seconds, using Instant.now()
.
Instant instant = Instant.now() ;
Generating text
Your desired format complies with the ISO 8601 standard. Those standard formats are used by default in the java.time classes when parsing/generating strings.
String output = instant.toString() ; // Generate text in standard ISO 8601 format.
And parsing.
Instant instant = Instant.parse( "2021-07-11T16:53:45.604Z" ) ;
Z
is not decoration
By the way, regarding your formatting pattern, yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
, never put single quotes around the Z
. The Z
represents vital information, the offset-from-UTC. Your quotes kill that, turning it into a mere string literal.