Android中Calendar與Date的區別以及消除時區對日期操作影響的方法
在Android中的日期操作常用的有三種方式,分別是:
Date類型
Calendar類型
Unix時間戳記
其中,Unix時間戳記在計算上最為方便和靈活,效率也高;而Date和Calendar則在一些具體的日期計算上更為便利。其中,在進行日期轉化的時候,經常會用到SimpleDateFormat類來進行格式化,包括將特定格式字串轉化為Date對象,以及將Date對象格式化為特定格式字串。
首先來比較一下Date和Calendar的不同。使用過日期轉Unix時間戳記的人很有可能會遇到一個問題,那就是Date或者SimpleDateFormat獲得的時間戳記跟Calendar獲得的時間戳記有差值,使用中國時區的話這個差值應該是28800000ms,也就是8小時。顯然,這8個小時的差別就是由於時區產生的,而如果在開發與日期時間緊密相關的程式時忽略了這一時差,很可能就會產生許多匪夷所思的誤差和結果。在Android中,Calendar是能夠自動根據手機所設定的時區來調整時間戳記的,也就是該時區真實的時間戳記;Date和SimpleDateFormat獲得的時間戳記則不考慮時區,而是擷取標準的GMT時間戳記。這兩者的時間戳記差可以通過使用TimeZone.getDefault().getRawOffset()方法來取得。那麼現在就可以很容易地得出解決Date、SimpleDateFormat與Calendar在時間戳記上的時差問題的方法,簡單描述如下:
Calendar calendar = Calendar.getInstance();//擷取當前日曆對象
long unixTime = calendar.getTimeInMillis();//擷取當前時區下日期時間對應的時間戳記
long unixTimeGMT = unixTime - TimeZone.getDefault().getRawOffset();//擷取標準格林尼治時間下日期時間對應的時間戳記
Date date = new Date();//擷取當前日期對象
unixTimeGMT = unixTime = date.getTimeInMillis();//擷取當前時區下日期時間對應的時間戳記
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設定格式
String dateString = "2010-12-26 03:36:25";//設定具有指定格式的日期文字
unixTimeGMT = unixTime = format.format(date);//擷取當前時區下日期時間對應的時間戳記
顯然,在開發中必須讓時間戳記統一,這樣才能避免許多尷尬的問題。那麼在實際開發過程中,究竟應該是使用手機指定時區的時間戳記還是標準時間戳記呢?個人認為應該使用標準時間戳記,因為使用者很有可能會有更改時區的操作出現,如果使用對應時區的時間戳記,並且時間戳記作為某種標記量存入了資料庫,那麼一旦時區發生改變,已存資料將會與當前時區設定產生問題;而使用標準時間戳記則可以避免這一問題,因為通過程式可以很容易地將時間戳記轉化為標準時間戳記,並且標準時間戳記是固定的,這樣就能保證即使在修改了時區的情況下,也能正確處理日期時間。
二. Android開發中 擷取當前Android的年月日時分秒的時間
Android的檔案有建議用Time代替Calendar。用Time對CPU的負荷會較小。在寫Widget時特別重要。
Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone資料。
package ***;
import android.app.Activity;
import android.os.Bundle;
import android.text.format.Time;
import android.widget.TextView;
public class ShowTime extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView myTextView = (TextView)findViewById(R.id.myTextView);
Time time = new Time("GMT+8");
time.setToNow();
int year = time.year;
int month = time.month;
int day = time.monthDay;
int minute = time.minute;
int hour = time.hour;
int sec = time.second;
myTextView.setText("目前時間為:" + year +
"年 " + month +
"月 " + day +
"日 " + hour +
"時 " + minute +
"分 " + sec +
"秒");
}
}
唯一不足是取出時間只有24小時模式.
========================================================================================
如何擷取Android系統時間是24小時制還是12小時制
ContentResolver cv = this.getContentResolver();
String strTimeFormat = android.provider.Settings.System.getString(cv,
android.provider.Settings.System.TIME_12_24);
if(strTimeFormat.equals("24"))
{
Log.i("activity","24");
} www.2cto.com
利用Calendar擷取年月日時分秒
Calendar c = Calendar.getInstance();
取得系統日期:year = c.get(Calendar.YEAR)
month = c.get(Calendar.MONTH)
day = c.get(Calendar.DAY_OF_MONTH)
取得系統時間:hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE)