广

android开发

  • IOS开发
  • android开发
  • PHP编程
  • JavaScript
  • ASP.NET
  • ASP编程
  • JSP编程
  • Java编程
  • 易语言
  • Ruby编程
  • Perl编程
  • AJAX
  • 正则表达式
  • C语言
  • 编程开发

    Android日期时间格式国际化的实现代码

    2018-04-07 07:49:13 次阅读 稿源:互联网
    广告

    在做多语言版本的时候,日期时间的格式话是一个很头疼的事情,幸好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

    一起学吧部分文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与一起学吧进行文章共享合作。

    广告
    广告
    广告