-4

How to convert "2017-07-12T18:43:04.000Z" to ago format like 1 hour ago or 1 week ago?

Vinit
  • 11

1 Answers1

0

You must convert your dtStart string to date object by SimpleDateFormat. After that you can get it in millisecond with date.getTime() method and calculate it's difference to current time. Now from this difference you can get the ago format you want:

public String getDate(String dtStart) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    try {
        Date date = format.parse(dtStart);

        long diff = System.currentTimeMillis() - date.getTime();
        long hours = Math.round(diff / (60 * 60 * 1000));


        if(hours < 24) {
            return hours + " hours ago";
        } else {
            long days = Math.round(diff / (24.0 * 60 * 60 * 1000));

            if (days == 0)
                return "today";
            else if (days == 1)
                return "yesterday";
            else if (days < 14)
                return days + " days ago";
            else if (days < 30)
                return ((int) (days / 7)) + " weeks ago";
            else if (days < 365)
                return ((int) (days / 30)) + " months ago";
            else
                return ((int) (days / 365)) + " years ago";
        }


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

    return "";
}
SiSa
  • 2,594
  • 1
  • 15
  • 33
  • 2
    While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem. – Joe C Jul 15 '17 at 22:13