Why if I use String.format(Date)
it prints date in default timezone, but when I use String.format(Calendar)
it prints in Calendar's timezone. Actually, the latter is what I need, but can I be sure that this behavior will persist?
Asked
Active
Viewed 220 times
0

dhblah
- 9,751
- 12
- 56
- 92
-
Date never has a time-zone and Calendar always does. Is that your doubt? – Peter Lawrey Oct 16 '12 at 11:44
-
1Check this post: -http://stackoverflow.com/questions/2891361/java-how-to-set-timezone-of-a-java-util-date to know how to set `TimeZone` for your date object. – Rohit Jain Oct 16 '12 at 11:47
-
@RohitJain that's impossible, date doesn't contain timezone info. – dhblah Oct 16 '12 at 12:18
-
Still, the post Rohit linked to contains your answer: use a `SimpleDateFormat` to format your date and set the timezone on the `SimpleDateFormat` object. – Jesper Oct 16 '12 at 12:28
-
Still, I was not asking about `SimpleDateFormat`, but about `String.format()`. – dhblah Oct 16 '12 at 12:36
1 Answers
1
As I found from implementation of String.format (at least for JDK 1.5, it has printDateTime(Object, Locale)
which contains such code:
} else if (arg instanceof Date) {
// Note that the following method uses an instance of the
// default time zone (TimeZone.getDefaultRef().
cal = Calendar.getInstance(l);
cal.setTime((Date)arg);
} else if (arg instanceof Calendar) {
cal = (Calendar) ((Calendar)arg).clone();
cal.setLenient(true);
} else {
so if argument for String.format
is of Date, Calendar.getInstance(Locale)
is used, which creates calendar in default timezone, if argument is Calendar
then calendar's time zone is used. Moreover, i didn't found any explicit description of this and that method is private, so It's impossible to assume that this behavior won't change.

dhblah
- 9,751
- 12
- 56
- 92