《Android应用开发攻略》——2.12 为显示格式化时间和日期

    xiaoxiao2022-05-31  192

    2.12 为显示格式化时间和日期

    Pratik Rupwal2.12.1 问题你希望以不同的标准格式显示时间和日期。2.12.2 解决方案DateFormat类提供API,用于以自定义格式表示时间和日期。这些API用起来毫不费力。2.12.3 讨论例2-15添加了5个不同的TextView控件,用于显示不同格式的时间和日期。例2-15:TextView布局

    <?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:id="@+id/textview1" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/textview2" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/textview3" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/textview4" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/textview5" /> </LinearLayout>

    例2-16 用java.util.Date类获取当前时间和日期,然后以不同的格式显示(样例输出参见注释)。例2-16:日期格式化活动

    package com.sym.dateformatdemo; import java.util.Calendar; import android.app.Activity; import android.os.Bundle; import android.text.format.DateFormat; import android.widget.TextView; public class TestDateFormatterActivity extends Activity { /**在活动第一次创建时调用 */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textView1 = (TextView) findViewById(R.id.textview1); TextView textView2 = (TextView) findViewById(R.id.textview2); TextView textView3 = (TextView) findViewById(R.id.textview3); TextView textView4 = (TextView) findViewById(R.id.textview4); TextView textView5 = (TextView) findViewById(R.id.textview5); String delegate = "MM/dd/yy hh:mm a"; // 09/21/2011 02:17 pm java.util.Date noteTS = Calendar.getInstance().getTime(); textView1.setText("Found Time :: "+DateFormat.format(delegate,noteTS)); delegate = "MMM dd, yyyy h:mm aa"; // Sep 21,2011 02:17 pm textView2.setText("Found Time :: "+DateFormat.format(delegate,noteTS)); delegate = "MMMM dd, yyyy h:mmaa"; //September 21,2011 02:17pm textView3.setText("Found Time :: "+DateFormat.format(delegate,noteTS)); delegate = "E, MMMM dd, yyyy h:mm:ss aa";//Wed, September 21,2011 02:17:48 pm textView4.setText("Found Time :: "+DateFormat.format(delegate,noteTS)); delegate = "EEEE, MMMM dd, yyyy h:mm aa"; //Wednesday, September 21,2011 02:17:48 pm textView5.setText("Found Time :: "+DateFormat.format(delegate,noteTS)); } }

    2.12.4 参阅下表中列出的android.text.format中的类,对这类应用程序可能有用。名称 用法DateUtils 该类包含各种与日期相关的工具,用于创建消耗时间和日期范围之类的 文本,代表周日和月份的字符串以及表示上/下午的文本Formatter 这是一个工具类,有助于格式化java.util.Formatter中不包含的常见值Time 该类是java.util.Calendar和java.util.GregorianCalendar的替代 品,速度更快

    相关资源:iOS软件开发揭密:iPhone&iPad;企业应用和游戏开发--详细书签版

    最新回复(0)