I want to convert a date to GMT.
I get a date in BST, I want to convert it to GMT without time zone conversion. Example: **If the BST date is: Wed June 26 13:30:13 BST 2019
I want to convert it to Wed 26 Jun 2019 13:30:13 GMT**
I want to ignore the timezone info and return the same date as GMT.
For this I am trying
private SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private SimpleDateFormat dateFormatGmtText = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss 'GMT'");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String textDate = dateFormatLocal.format(date);
//Date is Wed June 26 13:30:13 BST 2019
private Date toGMTDate(final Date date) {
String textDate = dateFormatLocal.format(date);
try {
String[] dateParts = textDate.split("\\+");
textDate = dateParts[0] + "+0000";
return dateFormatGmt.parse(textDate);
} catch (ParseException e) {
return null;
}
}
private String toGMT(final Date date) {
return dateFormatGmtText.format(toGMTDate(date));
}
When I call toGMT
it returns Wed 26 Jun 2019 14:30:13 GMT
I am not sure why it is so? What is wrong here?
Date
is just a number of milliseconds since the unix epoch. It doesn't have a time zone. It's unclear where your data is coming from, or in what format, but this sounds like something which is better fixed earlier on. I'd also strongly recommend using java.time rather thanDate
,SimpleDateFormat
etc.SimpleDateFormat
andDate
. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead useZonedDateTime
,OffsetDateTime
andDateTimeFormatter
, all from java.time, the modern Java date and time API.Date
in BST and you cannot convert to aDate
in GMT. An old-fashionedDate
object can have neither time zone nor GMT offset.