How to convert "2017-07-12T18:43:04.000Z" to ago format like 1 hour ago or 1 week ago?
Asked
Active
Viewed 645 times
-4
-
please follow this: https://stackoverflow.com/questions/6581605/do-we-have-a-timespan-sort-of-class-in-java – Proxytype Jul 15 '17 at 21:16
-
What did you try? – Jul 15 '17 at 21:17
-
have you searched google? – oziomajnr Jul 15 '17 at 21:19
-
yeah..couldn't figure anything out. – Vinit Jul 15 '17 at 21:44
-
1Step 1: Parse timestamp. Step 2: Compare timestamp with current time. Step 3: Declare victory. – Joe C Jul 15 '17 at 21:46
-
You should work with this guy https://stackoverflow.com/questions/45120995/how-to-format-time-with-to-timeago-in-android – OneCricketeer Jul 15 '17 at 21:57
-
I'm voting to close this question as off-topic because it's a zero-effort requirements dump. – EJoshuaS - Stand with Ukraine Jul 16 '17 at 00:08
1 Answers
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
-
2While 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