Android的Time class比Java的Calendar和GregorianCalendar class更簡單、快速。
The Time class is a faster replacement for the java.util.Calendar and java.util.GregorianCalendar classes.
-Android Reference
public class Time extends Object – Android Reference
Time是非常簡單、好用的class,內定的Fields已經有我們一般常用到的時間、日期,我們只要從裡面取出來就行了。日期格式支援RFC 2445及3339。
主程式
package tw.ncut.ee.e719.testproject; import android.app.Activity; import android.os.Bundle; import android.text.format.Time; import android.widget.TextView; public class TestProject extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findviews(); gettime(); } private TextView showtext; private Time time = new Time(); private Time t1 = new Time(); private void findviews(){ showtext = (TextView) findViewById(R.id.showtext); } private void gettime(){ time.setToNow(); t1.set(00,30,16,25,0,2011); showtext.setText("Today is " + time.year + "/" + time.month + "/" + time.monthDay + "\n" + "The time is now " + time.hour + ":" + time.minute + "\n" + "Timeformat 3339: " + time.format3339(true) + "\n" + "After 2011/01/25 16:30 ? " + time.after(t1)); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/showtext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> </LinearLayout>
這裡我們新增兩個Time類型的物件,time和t1。time是我們取出時間的物件,t1是我們比對時間用的。
在gettime()的第一行,我們用.setToNow()方法取得目前手機的時間。預設時間是1970年。第二行是將t1作為比較時間的參考點,用.set(int 秒, int 分, int 時, int 日,int 月,int 年)。
第三行將結果顯示在手機螢幕上。分別顯示Time class內定Fields的年月日和目前時間,用取出內定Fields的方式和.format3339方法。注意到月份是從0開始算而不是1。
目前時間和參考時間比對先後結果以布林值回傳。
在虛擬機上執行結果。
最後更新日期: 2020/09/21
喜歡這篇文章?立刻分享給朋友!
- 0share
- FB Messenger
- Line