This is a helper class that I use when distributing standard DateUtils for Android. It has advanced logic that for today's time slots it displays seconds or minutes or hours, while for other timestamps it will display a date.
You can customize the logic to suit your needs in the getTimeDiffString method. As a parameter, you should Date date = formatter.parse(dateString); timestamp Date date = formatter.parse(dateString); which you retrieve in the above code.
The logic of the code corresponds to the value of "timestamp", as you know, from Facebook or Twitter.
public class DateTimeUtils extends DateUtils { private static String mTimestampLabelYesterday; private static String mTimestampLabelToday; private static String mTimestampLabelJustNow; private static String mTimestampLabelMinutesAgo; private static String mTimestampLabelHoursAgo; private static String mTimestampLabelHourAgo; public static DateTimeUtils getInstance(Context context) { mCtx = context; if (instance == null) { instance = new DateTimeUtils(); mTimestampLabelYesterday = context.getResources().getString(R.string.WidgetProvider_timestamp_yesterday); mTimestampLabelToday = context.getResources().getString(R.string.WidgetProvider_timestamp_today); mTimestampLabelJustNow = context.getResources().getString(R.string.WidgetProvider_timestamp_just_now); mTimestampLabelMinutesAgo = context.getResources().getString(R.string.WidgetProvider_timestamp_minutes_ago); mTimestampLabelHoursAgo = context.getResources().getString(R.string.WidgetProvider_timestamp_hours_ago); mTimestampLabelHourAgo = context.getResources().getString(R.string.WidgetProvider_timestamp_hour_ago); } return instance; } public static boolean isYesterday(long date) { final Calendar currentDate = Calendar.getInstance(); currentDate.setTimeInMillis(date); final Calendar yesterdayDate = Calendar.getInstance(); yesterdayDate.add(Calendar.DATE, -1); return yesterdayDate.get(Calendar.YEAR) == currentDate.get(Calendar.YEAR) && yesterdayDate.get(Calendar.DAY_OF_YEAR) == currentDate.get(Calendar.DAY_OF_YEAR); } public static String[] weekdays = new DateFormatSymbols().getWeekdays();
while strings.xml contains:
<string name="WidgetProvider_timestamp_today">Today</string> <string name="WidgetProvider_timestamp_yesterday">Yesterday</string> <string name="WidgetProvider_timestamp_hour_ago">%s hour ago</string> <string name="WidgetProvider_timestamp_hours_ago">%s hours ago</string> <string name="WidgetProvider_timestamp_minutes_ago">%s minutes ago</string> <string name="WidgetProvider_timestamp_just_now">Just now</string>
Mathias conradt
source share