Android日期時間格式國際化的實現代碼

來源:互聯網
上載者:User

在做多語言版本的時候,日期時間的格式話是一個很頭疼的事情,幸好Android提供了DateFormate,可以根據指定的語言地區的預設格式來格式化。

直接貼代碼:

複製代碼 代碼如下:public static CharSequence formatTimeInListForOverSeaUser(

final Context context, final long time, final boolean simple,

Locale locale) {

final GregorianCalendar now = new GregorianCalendar();

// special time

if (time < MILLSECONDS_OF_HOUR) {

return "";

}

// today

final GregorianCalendar today = new GregorianCalendar(

now.get(GregorianCalendar.YEAR),

now.get(GregorianCalendar.MONTH),

now.get(GregorianCalendar.DAY_OF_MONTH));

final long in24h = time - today.getTimeInMillis();

if (in24h > 0 && in24h <= MILLSECONDS_OF_DAY) {

java.text.DateFormat df = java.text.DateFormat.getTimeInstance(

java.text.DateFormat.SHORT, locale);

return "" + df.format(time);

}

// yesterday

final long in48h = time - today.getTimeInMillis() + MILLSECONDS_OF_DAY;

if (in48h > 0 && in48h <= MILLSECONDS_OF_DAY) {

return simple ? context.getString(R.string.fmt_pre_yesterday)

: context.getString(R.string.fmt_pre_yesterday)

+ " "

+ java.text.DateFormat.getTimeInstance(

java.text.DateFormat.SHORT, locale).format(

time);

}

final GregorianCalendar target = new GregorianCalendar();

target.setTimeInMillis(time);

// same week

if (now.get(GregorianCalendar.YEAR) == target

.get(GregorianCalendar.YEAR)

&& now.get(GregorianCalendar.WEEK_OF_YEAR) == target

.get(GregorianCalendar.WEEK_OF_YEAR)) {

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("E", locale);

final String dow = "" + sdf.format(time);

return simple ? dow : dow

+ java.text.DateFormat.getTimeInstance(

java.text.DateFormat.SHORT, locale).format(time);

}

// same year

if (now.get(GregorianCalendar.YEAR) == target

.get(GregorianCalendar.YEAR)) {

return simple ? java.text.DateFormat.getDateInstance(

java.text.DateFormat.SHORT, locale).format(time)

: java.text.DateFormat.getDateTimeInstance(

java.text.DateFormat.SHORT,

java.text.DateFormat.SHORT, locale).format(time);

}

return simple ? java.text.DateFormat.getDateInstance(

java.text.DateFormat.SHORT, locale).format(time)

: java.text.DateFormat.getDateTimeInstance(

java.text.DateFormat.SHORT, java.text.DateFormat.SHORT,

locale).format(time);

}

注意這裡用的是java.text.DateFormat,還有另外一個java.text.format.DateFormat,後者不能指定locale。

詳細介紹見:http://developer.android.com/reference/java/text/DateFormat.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.