开发者

Android Date Timezones driving me nuts

I have a Android app that works with GPS module and a SQLite database. Everything sounds so nice in the beginning, but the horror comes when I need to work with Date() and timezones.

A little background

The GPS module has the possibility to get date from the satellite. This is a great thing and I need it in my application to assure valid data. The date returned from it is GMT time. This Date is inserted in a field in local database as StartTime. The StartTime is stored encrypted with AES. When I decrypt the StartTime, I need to convert it as a Date and keep the format as GMT.

What I do Get the data from the GPS in LocationListener:

gpsDate = new Date(location.getTime());

by having new Date() by default the GPS date is converted in the current time zone of the Device. So instead of having a nice Sun Dec 05 14:00:00 GMT 2010 time, I get Sun Dec 05 16:00:00 GMT+2 2010. Why does it do that ? I just wanted a new Date out of the getTime().

I insert the data in database:

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 
String date = outputFormat.format(gpsDate);

I retrieve the Date when I need it:

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String myStored = {decrypy from the database}
Date myStartDate = outputFormat.parse(myStoredDate);

myStored shows: 2010-12-05 14:00

myStartDate shows: Sun Dec 05 16:00:00 GMT+2 2010

There is something I am missing in here. I need to be able to get the Date in GMT format, insert it, convert it, compare it, calculate differences. I need the 开发者_高级运维Date in users Timezone only when I need to show it to him.

Please illuminate me.


The issue looks to be that you are not storing the time zone. You said it yourself that myStored, when retrieved from wherever you stored it, comes back without a TZ. Then, when you call parse on it, you force it to use GMT. Since GMT is 2 hours different from your local timezone, the time comes out 2 hours different.

In a nutshell, you should be able to take the sattelite time, use the simpledateformat with the z or Z option to format the output to wherever you are storing it. You shouldnt even use the setTimezone method at all. Then use the same dateformatter as before, and not a new one, to parse the incoming date from where you stored it.

After you have done that, before you send the output to the user, determine their timezone and then set the timezone on the data you have.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜