String != datetime
Do not conflate a date-time object with a string that may represent its value.
A date-time object has no format. A date-time format represents a moment. A date-time object can generate a string. A date-time object can be created by parsing a string. But the date-time object and the string are always separate and distinct.
Avoid legacy classes
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Using java.time
Instant instant = Instant.now(); // Current moment in UTC
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = instant.atZone( z ); // Same moment viewed as wall-clock time of particular region.
Generate a string to represent that object’s value in a certain format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-M-d (HH:mm:ss.S)" , Locale.US );
String output = zdt.format( f );
Dump to console.
System.out.println( "instant.toString(): " + instant ); // Standard ISO 8601 format.
System.out.println( "zdt.toString(): " + zdt ); // Standard ISO 8601 format.
System.out.println( "output: " + output ); // Custom format.
See this code run live at IdeOne.com.
instant.toString(): 2017-04-15T06:00:58.521Z
zdt.toString(): 2017-04-15T18:00:58.521+12:00[Pacific/Auckland]
output: 2017-4-15 (18:00:58.5)
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?