Maduro
Maduro

Reputation: 725

Android - Converting Date to Time ago but it is returning 48 years ago

I am trying to convert a date to timeago. Something that returns: 1 hour ago, 1 month, 2 months ago, 1 year ago.

This is an android app that gets blog posts from WordPress.

However, my current code returns (for every post) 48 years ago.

I tried to find an answer on the internet and yes most of the answers out there helped me, but I still got 48 years ago for every post.

Most of the answers out there didn't work for me.

Please note that I am not using Java 8. A lot of the answers recommended Java 8 but I can't use it.

public String parseDateToddMMyyyy(String time) {
    String inputPattern = "yyyy-MM-dd'T'HH:mm:ss";
    String outputPattern = "yyyy-MM-dd HH:mm:ss'Z'";
    SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
    SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);

    inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    Date date = null;
    String str = null;

    try {
        date = inputFormat.parse(time);
        str = outputFormat.format(date);

        long dateInMillinSecond = date.getTime();

        str = toDuration(dateInMillinSecond);

        Log.e("Blog - ", "Date " + date);
        //output for the dare is Sat May 19 22:59:42 EDT 2018

        Log.e("Blog - ", "Str " + str);
        //output is 48 years ago

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return str;
}

I also found these 2 methods that convert millisecond to time ago and I THINK that these two methods work finds. So, I think that the problem is the date. The date format is not converting into millisecond (Not sure).

public static final List<Long> times = Arrays.asList(
    TimeUnit.DAYS.toMillis(365),
    TimeUnit.DAYS.toMillis(30),
    TimeUnit.DAYS.toMillis(1),
    TimeUnit.HOURS.toMillis(1),
    TimeUnit.MINUTES.toMillis(1),
    TimeUnit.SECONDS.toMillis(1));

public static final List<String> timesString = 
    Arrays.asList("year","month","day","hour","minute","second");

public static String toDuration(long duration) {
    StringBuffer res = new StringBuffer();
    for(int i=0;i< times.size(); i++) {
        Long current = times.get(i);
        long temp = duration/current;
        if(temp>0) {
            res.append(temp).append(" ").append(timesString.get(i))
            .append(temp != 1 ? "s" : "").append(" ago");
            break;
        }
    }
    if("".equals(res.toString()))
        return "0 seconds ago";
    else
        return res.toString();
}

EDIT

The variable long dateInMilliSecond is returning 1524430807000

Upvotes: 0

Views: 539

Answers (2)

Pedro Massango
Pedro Massango

Reputation: 5025

This complete code will get what you want, just use the method getTimeAgo() giving the time in milliseconds.

// TIME AGO
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;

public static String concat(Object... args) {
    String joineed = "";
    for (Object s : args) {
        joineed = joineed + " " + s;
    }
    return joineed;
}

public static String getTimeAgo(long time) {

    String MIN = " min";
    String HR = "h";
    String HA = "há";

    if (time < 1000000000000L) {
        // if timestamp given in seconds, convert to millis
        time *= 1000;
    }

    long now = System.currentTimeMillis();
    if (time <= 0) {
        return null;
    } else if (time > now) {
        time = now;
    }

    final long diff = now - time;
    if (diff < MINUTE_MILLIS) {
        return "agora";
    } else if (diff < 2 * MINUTE_MILLIS) {
        return concat(HA, join("1 ", MIN));
    } else if (diff < 50 * MINUTE_MILLIS) {
        return concat(HA, join((diff / MINUTE_MILLIS), MIN));
    } else if (diff < 90 * MINUTE_MILLIS) {
        return concat(HA, join("1 ", HR));
    } else if (diff < 24 * HOUR_MILLIS) {
        return concat(HA, join((diff / HOUR_MILLIS), HR));
    } else if (diff < 48 * HOUR_MILLIS) {
        return concat(HA, "1 d");
    } else if ((diff / DAY_MILLIS) > 30) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int month = c.get(Calendar.MONTH) + 1;
        int year = c.get(Calendar.YEAR);
        return String.format("%s/%s/%s", day, month, year);
    } else {
        return concat(HA, join((diff / DAY_MILLIS), "d"));
    }
}

public static long getTime() {
    return System.currentTimeMillis();
}

You can also se the complete code on this gist: https://gist.github.com/pedromassango/93128cc1b338d0df19fa5f89b72eeea9

Upvotes: 1

Abdullah G&#252;rsu
Abdullah G&#252;rsu

Reputation: 3186

I will look at your code but I should definitely say that, 48 years ago reminds me 1 Jan 1970. Probably you're sending null or 0 as date to humanizer function.

Edit After Review:

I think the problem is that, you're calculating duration of a date, not difference. If you want to calculate a real date ago, you should send time difference to toDuration function.

Current behavior is quite normal because you send a x-x-2018 date to toDuration function and it returns 48 years ago basically(since zero is 1970). You should send the difference. For example;

long difference = System.currentTimeMillis() - dateInMillisecond;
String humanizedDate = toDuration(difference);

Upvotes: 3

Related Questions