In multi-language versions, the date and time format is a headache. Fortunately, Android provides DateFormate, which can be formatted Based on the default format of the specified language region.
Directly paste the Code:
Copy codeThe Code is as follows: 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 in24 H = time-today. getTimeInMillis ();
If (in24 h> 0 & in24 H <= MILLSECONDS_OF_DAY ){
Java. text. DateFormat df = java. text. DateFormat. getTimeInstance (
Java. text. DateFormat. SHORT, locale );
Return "" + df. format (time );
}
// Yesterday
Final long in48 H = time-today. getTimeInMillis () + MILLSECONDS_OF_DAY;
If (in48 h> 0 & in48 H <= 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 );
}
Note that java. text. DateFormat is used here, and another java. text. format. DateFormat is used. The latter cannot specify locale.
For details, see: http://developer.android.com/reference/java/text/DateFormat.html