Android 取得當前時間

Android的文件有建議用Time代替Calendar。用Time對CPU的負荷會較小。在寫Widget時特別重要。

Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone資料。

    package itokit.com;      
         
    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小時模式.


long time=System.currentTimeMillis();
 final Calendar mCalendar=Calendar.getInstance();
 mCalendar.setTimeInMillis(time);
 取得小時:mHour=mCalendar.get(Calendar.HOUR);
 取得分鐘:mMinuts=mCalendar.get(Calendar.MINUTE);

 

 如何獲取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");
        }

Calendar c = Calendar.getInstance();
取得系統日期:year = c.get(Calendar.YEAR)
               month = c.grt(Calendar.MONTH)
               day = c.get(Calendar.DAY_OF_MONTH)
取得系統時間:hour = c.get(Calendar.HOUR_OF_DAY);
                  minute = c.get(Calendar.MINUTE)


利用Calendar獲取
 Calendar c = Calendar.getInstance();
取得系統日期:year = c.get(Calendar.YEAR)
               month = c.grt(Calendar.MONTH)
               day = c.get(Calendar.DAY_OF_MONTH)
取得系統時間:hour = c.get(Calendar.HOUR_OF_DAY);
                  minute = c.get(Calendar.MINUTE)
                    Calendar c = Calendar.getInstance();
取得系統日期:year = c.get(Calendar.YEAR)
                   month = c.grt(Calendar.MONTH)
                   day = c.get(Calendar.DAY_OF_MONTH)
取得系統時間:hour = c.get(Calendar.HOUR_OF_DAY);
                     minute = c.get(Calendar.MINUTE)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章