java - Weird mysql beahviours with timezones? How to control them? -
i wrote webapp using spring+hibernate. developed on windows , moved linux virtual server (aruba, italian provider). noticed annoying thing: when dates saved on windows time same of "wall clock", if read 13:45 have same hour in mysql row. doesn't happen on linux anyway. in fact linux machine on cest (my timezone), got typing "date" in shell. dates saved in db offset relative gmt. again, app displays in gmt (including gmt time zone if choose format dates display time zone) , mysql saves in format. how control this?
i post solution myself, because think it's worth having in site.
first of all: mysql doesn't store timezone information. running on gmt+4 , write couple of records contain date fields. move system in gmt-2 read records (perhaps importing data mysqldump). if system , vm have gmt-2 timezone dates read taken if written in gmt-2 , not adjusted.
solution: take control of vm timezone using -duser.timezone="gmt" command line option (you can put in tomcat startup script) or preferred timezone (but gmt better, let me explain why). way you'll know for sure timezone vm running. doesn't mean java vm assume system time 1 specified in user.timezone, know system timezone , adjust dates accordingly. in fact if not in gmt, see dates in adjusted gmt , saved db accordingly. way you'll sure using reference.
the problem if take date object , mydateobject.tostring(), you'll date adjusted gmt, hour offset. not you'll want.
the solution use simpledateformat , somthing when have output date:
simpledateformat dateformat = new simpledateformat( "hh:mm dd/mm/yyyy z", locale.italy); dateformat.settimezone(timezone.gettimezone("europe/rome")); everything converted right way. can go further if developing web app. can extract timezone httprequest , adjust date output accordingly, didn't go far i'm writing application intended italian users :d (yay).
hope help.
Comments
Post a Comment