2010年9月2日星期四

DateFormat 和 SimpleDateFormat

DateFormat是一個格式化和解析日期或時間的抽象類. 它的子類, 如SimpleDateFormat, 允許進行格式化(即date -> text), 分析(text -> date), 規範化. 該日期以Date對象表示, 或自1970年1月1日, 格林尼治標準時間(GMT)00:00:00起以毫秒表示.

SimpleDateFormat是一個用於本土(locale-sensitive)格式化和解析日期方式的具體類.

時間格式語法
要指定的時間格式, 使用時間模式字符串. 在這個模式中, 所有的ASCII字母被保留為模式字母, 其中定義如下:

Symbol Meaning Presentation Example
G era designator (Text) AD
y year (Number) 1996
M month in year (Text & Number) July & 07
d day in month (Number) 10
h hour in am/pm (1˜12) (Number) 12
H hour in day (0˜23) (Number) 0
m minute in hour (Number) 30
s second in minute (Number) 55
S fractional second (Number) 978
E day of week (Text) Tuesday
D day in year (Number) 189
F day of week in month (Number) 2 (2nd Wed in July)
w week in year (Number) 27
W week in month (Number) 2
a am/pm marker (Text) PM
k hour in day (1˜24) (Number) 24
K hour in am/pm (0˜11) (Number) 0
z time zone (Text) Pacific Standard Time
Z time zone (RFC 822) (Number) -0800
v time zone (generic) (Text) Pacific Time
V time zone (location) (Text) United States (Los Angeles)
' escape for text (Delimiter) 'Date='
'' single quote (Literal) 'o''clock'


實例:

SimpleDateFormat實例

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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/currenttime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

AndroidSimpleDateFormat.java
package com.AndroidSimpleDateFormat;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidSimpleDateFormat extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView currentTime = (TextView)findViewById(R.id.currenttime);

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm:ss a");
String now = formatter.format(new Date());

currentTime.setText("Now is: " + now);

}
}

1 則留言:

  1. 感謝!!!
    這其實是最實在的一篇文章

    加註在公司文件中

    回覆刪除