2013-03-11 82 views
0

如果設備的時區不正確時間將返回不正確的值,而日曆將工作。我的應用程序是用Time創建的,我想保留它,但我需要修復時區問題。如果時區不正確,時間返回錯誤的值

Calendar c = Calendar.getInstance(); 
String out= c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE); 
Toast.makeText(this, ""+out, Toast.LENGTH_SHORT).show(); 
//returns correct time 

Time currentTime = new Time(); 
currentTime.setToNow(); 
Toast.makeText(this, currentTime.format("%H:%M"), Toast.LENGTH_SHORT).show(); 
//returns incorrect time 
+0

這不只是GIGO? – djechlin 2013-03-11 00:36:40

+0

什麼是不正確的值? – StarPinkER 2013-03-11 00:40:23

+0

1小時20分鐘(而不是1.42是00:12) – 2013-03-11 00:42:36

回答

0

我不知道這是否會幫助你,但我有一個非常本地化的應用程序,所以我只是迫使時區從RES/strings.xml中的變量。

事情是這樣的:

Calendar currentTime = Calendar.getInstance(); 

SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa"); 
dateFormat.setTimeZone(TimeZone.getTimeZone(context.getString(R.string.app_timezone))); 

Toast.makeText(this, dateFormat.format(input.getTime()), Toast.LENGTH_SHORT).show(); 

然後在res/strings.xml中

<string name="app_timezone">GMT+8:00</string> 
+0

我可以讓它使用Calendar和SimpleDateFormat工作,但這需要我修復整個應用程序,並導致更高的電池消耗。 – 2013-03-11 10:45:21

+0

我很好奇它將如何增加電池消耗,但這一邊。我發現將所有這種邏輯轉換成實用工具類可以讓我做出相當容易的批量修改。如果你遇到了Time,你總是可以讓util實現Time並在內部使用Calendar。例如DateUtils.format(new Time()) – 2013-03-11 12:12:16