When I search online about "how to convert a Calendar
to a String
", all the results I find suggest to first convert to a Date
and then convert the Date
to a String
.
The problem is that a Date
is only a representation of the number of milliseconds since the epoch - it does not respect timezone. Calendar
is more advanced in this way.
Of course, I could call the individual Calendar.get
methods to create my own formatted string, but surely there must be an easier way?
To illustrate, I wrote this code:
long currentTime = Calendar.getInstance().getTimeInMillis();
Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
calendar.setTimeInMillis(currentTime);
System.out.println(calendar.getTime().toString());
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
While running this code from a machine based in London (UTC+0) at 8:02pm, I got the following results:
Wed Nov 18 20:02:26 UTC 2015
2015-11-18 20:02:26
21
The last line shows the real hour according to the calendar's timezone (Madrid which is UTC+1). It is 9:02pm in Madrid, but obviously both the native Date.toString
as well as the DateFormat.format
methods ignore the timezone because the timezone information is erased when calling Calendar.getTime
(similarly Calendar.getTimeInMillis
).
Given this, what is the best way to get a formatted string from a Calendar
which respects timezone?