tl;dr
Instant.now().toString()
2020-03-08T00:21:48.647951Z
java.util.Date::toString
tells a lie
Your call to GregorianCalendar::getTime
returns a java.util.Date
. As you can see with this method and class naming, these classes are badly designed.
Then you implicitly called Date::toString
to generate text that represents the value within that object. That value is actually in UTC, being merely a count of milliseconds since the epoch reference of first moment of 1970 in UTC. Unfortunately, that method dynamically applies the JVM’s current default time zone while generating the text. This creates the illusion of that zone being contained within the object.
Confusing? Yes. One of many reasons to never use these legacy date-time classes. Use java.time classes instead.
java.time
The other Answers are correct, but now obsolete. The terrible Date
, Calendar
, GregorianCalendar
, and SimpleDateFormat
classes were years ago supplanted by the modern java.time classes defined in JSR 310.
To get the current moment in UTC, use Instant
. This basic building block class in java.time is always in UTC, by definition.
Instant instant = Instant.now() ;
Generate a string in standard in ISO 8601 format by calling toString
.
String output = instant.toString() ;
See this code run live at IdeOne.com.
2020-03-08T00:21:48.647951Z
For more flexible formatting when generating strings, use the OffsetDateTime
class. Search Stack Overflow to learn about DateTimeFormatter
.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;