I am newbie to java and android. One of my android news app i am displaying the time as "7 August 2014, 8:20 am"
But I need to display it like:
5 mins ago 1 hour ago 2 days ago
Found many libraries such us pretty time, joda. But i dont know how to add it to my android app. Even this link https://stackoverflow.com/a/13018647/2020685 show me. But how to pass my date and time into it.
Any simple code to do it.
Thanks
In Android you can use DateUtils. getRelativeTimeSpanString(long timeInMillis), referring to https://developer.android.com/reference/android/text/format/DateUtils.html you can use one of the variations of that method for accuracy. Show activity on this post. Show activity on this post.
Calendar Date currentTime = Calendar. getInstance(). getTime();
Current versions of Android use the latest Java language and its libraries (but not full graphical user interface (GUI) frameworks), not the Apache Harmony Java implementation, that older versions used. Java 8 source code that works in latest version of Android, can be made to work in older versions of Android.
As Kotlin is interoperable with Java, we will be using the Java utility class and Simple Date Format class in order to get the current local date and time.
What you want to display is called as the Relative time display. Android provides methods to display time relative to your current time. You don't have to use any third party library just for this purpose.
You can use
DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution)
eg.
DateUtils.getRelativeTimeSpanString(your_time_in_milliseconds, current_ time_in_millisecinds,DateUtils.MINUTE_IN_MILLIS);
UPDATE1:
You can try following to pass your date and get the milliseconds for it.
public static long getDateInMillis(String srcDate) { SimpleDateFormat desiredFormat = new SimpleDateFormat( "d MMMM yyyy, hh:mm aa"); long dateInMillis = 0; try { Date date = desiredFormat.parse(srcDate); dateInMillis = date.getTime(); return dateInMillis; } catch (ParseException e) { Log.d("Exception while parsing date. " + e.getMessage()); e.printStackTrace(); } return 0; }
Hope it helps you.
Create the below logic:
% it by 3600*365
result > 0
then display year(s) agoelse % it by 3600 * 30
result > 0
then display month(s) agoelse % it by 3600 * 7
result > 0
then display week(s) agoelse % it by 3600
result > 0
then display day(s) agoelse % it by 3600 / 24
result > 0
then display hour(s) agoelse % it by 60
, result > 0
then display minute(s) agoNOTE: % means mod (modulus operation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With