wrong time shown in Datefield related to TimeZones in Blackberry
I have a problem relating to a countdown based on a DateField.
App - set a DateField including a default Value (10 minutes) - get the value of the field, start a thread and reduce the 开发者_高级运维value every second - show the new value every second on a screen
Problem If my simulator/device is GMT everything works fine. But if I change the DateField and result screen shows a wrong value.
Here the Datefield is and default value is set
long time = 1000*60*DEFAULT_PARKING;
parkingTimePicker = new DateField("",time, DateField.TIME);
TimeZone zone = TimeZone.getTimeZone("GMT");
parkingTimePicker.setTimeZone(zone);
Afterwards the remaining seconds are reduced every second.
Here the remaining time in the thread is translated from seconds back to hh:mm:ss
public void showTimeLeft()
{
private long timeLeft; //time left in Seconds
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
private Date resultdate;
resultdate = new Date(timeLeft*1000);
mainScreen.setRemainingTimeLabel(sdf.format(resultdate));
}
Here the method which shows the value on the mainscreen
public void setRemainingTimeLabel(String text)
{
remainingTimeLabel.setText(text);
add(new LabelField(System.currentTimeMillis()+""));
add(new LabelField(text));
}
I am not sure where I made the mistake but I am pretty sure it is related to the Timezone. How can I make sure my app works in different timezones?
I believe you misused DateField
. It is designed to manipulate with timestamps (which include the date itself + time within the date). Yes, DateField
may show only time part of the timestamp, however its constructor expects a long
representing a full timestamp (both date + time parts). So by passing long time = 1000*60*DEFAULT_PARKING
what date do you pass? I'd recommend to use something like this:
int millisSinceMidnight = 1000 * 60 * DEFAULT_PARKING;
// Retrieves date relative to midnight on current day.
Calendar dateCal = DateTimeUtilities.getDate(millisSinceMidnight);
long time = dateCal.getTime().getTime();
parkingTimePicker = new DateField("", time, DateField.TIME);
It is unclear how do you calculate timeLeft
. Probably post the code if the issue is still present after reading/using this post.
I also believe SimpleDateFormat
formats time using the current device timezone. So your code only works if device timezone is GMT. To workaround this you should remove this:
TimeZone zone = TimeZone.getTimeZone("GMT");
parkingTimePicker.setTimeZone(zone);
so both picker and formatter work in the same timezone (current on the device).
精彩评论