As a rule, you never change the default time zone only for your local advantages, since this affects all the code in the JVM - perhaps it wants the actual local time zone to be the default. Therefore, using TimeZone.setDefault () is bad practice if you are not sure that all of your code will want this time zone and that all of your code is yours and that this will never change. This is a lot to ask.
Instead, you should explicitly specify the time zone of interest for your calls.
Once you get an instance of DateFormatter, you'll want to call setTimeZone (TimeZone.getTimeZone ('UTC')) . This will make this formatter use this time zone. You can also use any other time zone.
Finally, you call the dateFormat.format (Date date) method to get a string representation of that date in the locale, style, and time zone of the selection.
If you DO NOT want a locale-specific format, but want to fix something of your own, such as ISO, instead of creating an instance of DateFormat using the static factory method described above, you will want to use SimpleDateFormat . In particular, you will use the constructor of the new SimpleDateFormat (String pattern) template . The template will follow the definitions in the JavaDoc SimpleDateFormat and may be, for example, "yyyy-MM-dd HH: mm: ss.SSS".
Then you call the setTimeZone () method for the SimpleDateFormat instance the same as for (any) DateFormat. In Groovy, you can skip the explicit creation of SimpleDateFormat, and instead you can use the Groovy Date extension, its format (String format, TimeZone tz) - this will do the SimpleDateFormat material under the covers.
An example approach to a specific format format (Java and / or Groovy):
String gimmeUTC(Date date, Locale locale) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat.format(date); }
An example of a fixed format approach (Java and / or Groovy):
String gimmeUTC(Date date, Locale locale) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat.format(date); }
Fixed format example (Groovy only):
String gimmeUTC(Date date) { return date.format('yyyy-MM-dd HH:mm:ss.SSS', TimeZone.getTimeZone('UTC')); }