Kaidul
Kaidul

Reputation: 15885

How to get the amount of passed time till now from a given unix timestamp

I am given a unix timestamp and I need to find the difference of seconds/min/hour by comparing with current time. I need something like:

34 sec ago
1 min ago
4 mins ago
5 hours ago
1 days ago
2 days ago

I have tried some poor if-else styled code but it is giving wrong wierd output

String time = null;
long quantity = 0;
long addition = 0;
long diffMSec = System.currentTimeMillis() - Long.parseLong(submissionInfo
        .get(CommonUtils.KEY_SUBMISSION_TIME)) * 1000L;
diffMSec /= 1000L;
if (diffMSec < 86400L) { // less than one day
    if (diffMSec < 3600L) { // less than one hour
        if (diffMSec < 60L) { // less than one minute
            quantity = diffMSec;
            time = "sec ago";
        } else { // greater than or equal to one minute
            addition = (diffMSec % 60L) > 0 ? 1 : 0;
            quantity = (diffMSec / 60L) + addition;
            if (quantity > 1)
                time = "mins ago";
            else
                time = "min ago";
        }
    } else { // greater than or equal to one hour
        addition = (diffMSec % 3600L) > 0 ? 1 : 0;
        quantity = (diffMSec / 3600L) + addition;
        if (quantity > 1)
            time = "hours ago";
        else
            time = "hour ago";
    }
} else { // greater than or equal to one day
    addition = (diffMSec % 86400) > 0 ? 1 : 0;
    quantity = (diffMSec / 86400) + addition;
    if (quantity > 1)
        time = "days ago";
    else
        time = "1 day ago";
}
time = quantity + " " + time;

I need some working code with smarter approach or even any approach with working solution. Help me to figure it out.

Upvotes: 1

Views: 929

Answers (1)

Skaard-Solo
Skaard-Solo

Reputation: 682

I think you should use Calendar

Calendar cal = Calendar.getInstance();

String time = "yourtimestamp";
long timestampLong = Long.parseLong(time)*1000;
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);

Calendar implements Comparable so ...

long subs = Math.abs(cal.getTimeInMillis()  c.getTimeInMillis());
Calendar subCalendar = (Calendar)cal.clone();
subCalendar.setTimeInMillis(subs);

You can also use this link, because it seems to be a problem like yours

Upvotes: 1

Related Questions