Is there any source code for turning the timeInMills to a 24hour/Date like from the messenger app. When the timeInMills is below 24 hour it will return like this 16:15
but when it is over 24hour it will return like this THU at 16:15
. I am currently creating a chat app and I want to add this to my app.
Edit
Beware this line: long last24hTimestamp = current - MILLISECONDS_PER_DAY;
I'm calculating on behalf of UTC time.
To get the local time, you should take into account the timezone.
So basically you have to calculate if the timestamp timeInMillis
is within the last 24h then use one format otherwise use another format.
This will help you:
public static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;// In real app you should pre-calculate this value
public static final String RECENT_DATE_FORMAT = "HH:mm";
public static final String OLD_DATE_FORMAT = "E' at 'HH:mm";
public static String displayTime(long timestamp) {
long current = System.getCurrentTimeMillis();
long last24hTimestamp = current - MILLISECONDS_PER_DAY;
if (timestamp > last24hTimestamp) {
// Received message within a day, use first format
SimpleDateFormat sdf = new SimpleDateFormat(RECENT_DATE_FORMAT);
return sdf.format(new Date(timestamp));
} else {
// Message is older than 1 day. Use second format
}
}
Something you should take care of:
Consider parsing with timezone/localization if your app run in multiple places
If you're using java 8, try to use DateTimeFormatter
. It's threadsafe and you can use a static instance per date format, no need to initialize SimpleDateFormat
everytime you want to format a date