date and time in Android

本文總結Android中有關時間日期的用法

1、用示例介紹Date、DateFormat、Calendar的用法

Date date = new Date();//current time,values come from System.currentTimeMillis
Log.println(Log.INFO, TAG, "Date:"+date.getYear()+"-"+date.getMonth()+"-"+date.getDay()
		+"-"+date.getHours()+"-"+date.getMinutes()+"-"+date.getSeconds());
//abstract class,format a date for display to a human
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH-mm-ss E");
String dateTime = dateFormat.format(date);
Log.println(Log.INFO, TAG, dateTime);
//default Locale,default TimeZone,current date and time
//break down a date if you need to extract fields
Calendar calendar = Calendar.getInstance();//abstract class
Log.println(Log.INFO, TAG, calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)
		+"-"+calendar.get(Calendar.DAY_OF_MONTH)+"-"+calendar.get(Calendar.HOUR)
		+"-"+calendar.get(Calendar.MINUTE)+"-"+calendar.get(Calendar.SECOND));

2、System、SystemClock、Thread對時間的支持

用一個示例演示用法,any question可查看代碼中的註釋。

public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();
	long start = SystemClock.elapsedRealtime();
	long start_up = SystemClock.uptimeMillis();
	/**milliseconds running in the current thread*/
	long start_app = SystemClock.currentThreadTimeMillis();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//add all top-level views to screen
		getWindow().setContentView(R.layout.activity_main);
		findViewById(R.id.btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new Thread(){
					public void run() {
						super.run();
						//regardless of the system's time zone
						//called "Unix time" or "epoch time"
						//depends on system time
						long time1 = System.currentTimeMillis();//since January 1, 1970 00:00:00.0 UTC
						Log.println(Log.INFO, TAG, "System.currentTimeMillis:"+time1+"ms");
						//Equivalent to Linux's CLOCK_MONOTONIC
						//only be used to measure a duration by comparing it against another timestamp on the same device
						long time2 = System.nanoTime();//since booted
						Log.println(Log.INFO, TAG, "System.nanoTime:"+time2+"ns");
						SystemClock.sleep(500);
						long time3 = SystemClock.elapsedRealtimeNanos();//17
						try {
							//The precision is not guaranteed, the Thread may sleep more or less than requested
							Thread.sleep(500, 500000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						Log.println(Log.INFO, TAG, "Thread.sleep:"+(SystemClock.elapsedRealtimeNanos()-time3)+"ns");
					};
				}.start();
			}
		});
	}
	@Override
	protected void onResume() {
		Log.println(Log.INFO, TAG, "onResume");
		Log.println(Log.INFO, TAG, "sleep:"+(SystemClock.elapsedRealtime()-start)+"ms");
		Log.println(Log.INFO, TAG, "non-sleep:"+(SystemClock.uptimeMillis()-start_up)+"ms");
		super.onResume();
	}
	@Override
	protected void onPause() {
		Log.println(Log.INFO, TAG, "onPause");
		start = SystemClock.elapsedRealtime();
		start_up = SystemClock.uptimeMillis();
		start_app = SystemClock.currentThreadTimeMillis();
		Log.println(Log.INFO, TAG, start+"ms"+"-"+start_up+"ms"+"-"+start_app+"ms");//what's the difference?
		Log.println(Log.INFO, TAG, "start-start_up="+(start-start_up));//deep sleep time
		super.onPause();
	}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button 
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sleep"/>
</LinearLayout>

下面異常由Thread.sleep(long,int)拋出

3、詳細介紹DateFormat的用法

DateFormat使用了簡單工廠模式,其中工廠角色與抽象產品角色合併,具體產品角色只有SimpleDateFormat

//均爲SimpleDateFormat實例
DateFormat[] dateFormats = {DateFormat.getDateInstance(),
		DateFormat.getDateTimeInstance(),
		DateFormat.getTimeInstance()};
for(DateFormat df:dateFormats){
	Log.d(TAG, df.format(new Date(0L)));
	df.setTimeZone(TimeZone.getTimeZone("UTC"));
	Log.d(TAG, df.format(new Date(0L)));
}
Locale[] locales = DateFormat.getAvailableLocales();
//locale.toLanguageTag() API 21
for(Locale locale:locales){
	Log.d(TAG, "Locale:"+locale.toString());
}
String[] ids = TimeZone.getAvailableIDs();
for(String id:ids){
	Log.d(TAG, "id:"+id);
}
//SHORT, MEDIUM, LONG, FULL, or DEFAULT
Log.d(TAG, DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINA).format(new Date(0L)));
Log.d(TAG, DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK).format(new Date(0L)));//DEFAULT 2
Log.d(TAG, DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(new Date(0L)));
Log.d(TAG, DateFormat.getDateInstance(DateFormat.FULL, Locale.TAIWAN).format(new Date(0L)));

toLanguageTag方法在21引入,在低於21的設備會報如下異常

發佈了56 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章