First, for any date/time manipulation on Android, I highly recommend using the ThreeTenABP
library. This is a back port of the Java 8 java.time.*
package, circumventing the notoriously disappointing java.util.Date
and java.util.Calendar
classes.
To parse your "date_time"
using this library, you can use the following code:
// I set the ZoneId to systemDefault, but you should really use the ZoneId of the server
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
.withZone(ZoneId.systemDefault());
Instant instant = formatter.parse(m.dateTime(), Instant.FROM);
Android provides the DateUtils
class to display date and time information. This class takes into account system settings such as Locale
and 12/24-hour format. Therefore, if the Locale
of the device is set to any of the Arabic locales (ar_
), the date/time will be displayed in a format suited for it.
String display = DateUtils.getRelativeTimeSpanString(
instant.toEpochMilli(),
Instant.now().toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
The last parameter in getRelativeTimeSpanString
is the minimum resolution, so setting DateUtils.MINUTE_IN_MILLIS
will not display the difference in seconds.
If you insist on using the Java 7 classes, here is the same code using them:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(m.dateTime());
String display = DateUtils.getRelativeTimeSpanString(
date.getTime(),
new Date(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
If you need a "transition resolution" greater than a single day (i.e. you want to display a date/time that is further than one day in the past as "… days ago") you can use the DateUtils.getRelativeDateTimeString()
method instead:
String display = DateUtils.getRelativeDateTimeString(
mContext,
instant.toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL);
Any date that is further back than the transitionResolution
(in this case, one week) will be displayed in an appropriate date format, instead of the relative format. The minResolution
and transitionResolution
can be any long
value, DateUtils
contains other convenient constants such as MONTH_IN_MILLIS
and YEAR_IN_MILLIS
.
The last parameter takes an integer for formatting flags. These flags override the default formatting that DateUtils
uses for each Locale
; view the documentation for more information.