java - Calendar.getInstance().getTime() returning date in "GMT" instead of Default TimeZone -
calendar c = calendar.getinstance(); system.out.println(c.gettime()); c.set(2007, 0, 1); system.out.println(c.gettime());
output:
tue sep 12 12:36:24 ist 2017
mon jan 01 12:36:24 ist 2007
but, when use same code in different environment, output changes below:
output:
tue sep 12 12:36:24 ist 2017
mon jan 01 12:36:24 gmt 2007
fyi, tried print timezone of calendar instance, before , after setting values , both in "ist".
i want know root cause of this.
the second output in question correct , expected behaviour on jvm running irish time (europe/dublin). on september 12, 2017 ireland on summer time (dst). while not documented, date.tostring()
(which invoke implicitly when printing date
c.gettime()
) prints date , time in jvm’s time zone, in september rendered ist irish summer time.
when set date on calendar
object using irish time, hour of day preserved; in case jan 01 2007 12:36:24 irish standard time. imagine confusion if both irish summer time , irish standard time rendered ist. not able distinguish. instead, since irish standard time coincides gmt, date.tostring()
prints when date not in summer time part of year (which january isn’t).
my guess first output jvm running india time. rendered ist, , since india doesn’t use summer time, same abbreviation given summer , winter.
java.time
before understanding explanation behaviour observed, posted comment outdated , modern java date , time classes. still don’t think comment way off, though. modern equivalent of code:
zoneddatetime zdt = zoneddatetime.now(zoneid.of("europe/dublin")); system.out.println(zdt); zdt = zdt.with(localdate.of(2007, month.january, 1)); system.out.println(zdt);
it prints
2017-09-12t11:45:33.921+01:00[europe/dublin] 2007-01-01t11:45:33.921z[europe/dublin]
if want use jvm’s time zone setting, use zoneid.systemdefault()
instead of zoneid.of("europe/dublin")
. name states, contrary date
, zoneddatetime
include time zone. corresponds more old calendar
class. can see, tostring
method prints offset utc (z
meaning 0 offset) , time zone name in unambiguous region/city format. believe leaves lot less room confusion. if want print date in specific format, use datetimeformatter
.
appendix: sample output code
for sake of completeness, here outputs code when running different time zones may rendered ist:
europe/dublin (agrees second output)
tue sep 12 11:19:28 ist 2017 mon jan 01 11:19:28 gmt 2007
asia/tel_aviv
tue sep 12 13:19:28 idt 2017 mon jan 01 13:19:28 ist 2007
asia/kolkata (agrees first output)
tue sep 12 15:49:28 ist 2017 mon jan 01 15:49:28 ist 2007
Comments
Post a Comment