First, you shouldn’t have a Date
object. The Date
class is long outdated (no pun intended). Today you should prefer to use java.time
, the modern and much nicer date and time API. However, I am assuming that you are getting a Date
from some legacy API that you cannot change. The first thing you should do is convert it to an Instant
. Instant
is the corresponding class in java.time
. Then you should do any further operations from there.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MMMM-dd-yyyy h:mm:ss a z", Locale.US);
ZoneId desireedZone = ZoneId.of("Etc/GMT");
Date yourOldfashionedDate = // …;
ZonedDateTime dateTimeInGmt = yourOldfashionedDate.toInstant().atZone(desireedZone);
String formattedDateTime = dateTimeInGmt.format(formatter);
System.out.println(formattedDateTime);
This snippet prints the desired:
June-27-2018 5:33:00 PM GMT
Converting directly from the Date
object is safer and easier than converting from its string representation. The biggest problem with the latter is that the string contains CDT
as time zone, which is ambiguous. It may stand for Australian Central Daylight Time, North American Central Daylight Time, Cuba Daylight Time or Chatham Daylight Time. You cannot be sure which one Java is giving you. Never rely on three and four letter time zone abbreviations if there is any way you can avoid it.
Link: Oracle tutorial: Date Time explaining how to use java.time
.