Created
March 12, 2018 14:28
-
-
Save SergeyKharuk/ccdff6edb1ec734ce25eccb9fca3d81e to your computer and use it in GitHub Desktop.
Method which returns age of event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* helpful method. | |
* | |
* Condition: '_date' must be GMT +0; | |
* | |
* Returns the time values that passed. (e.g. 4m ago, 18h ago, 5d ago...etc); | |
*/ | |
public static String getAgeOfMessage(String _date){ | |
String dateString = DateTimeConverter.getDate(_date) + " " + DateTimeConverter.getTimeWithoutOffset(_date); | |
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); | |
dateFormat.setLenient(false); | |
Date createdDate = new Date(); | |
try { | |
createdDate = dateFormat.parse(dateString); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
} | |
createdDate.setHours(createdDate.getHours() + getTimeOffset()); | |
// SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd"); | |
long difference = System.currentTimeMillis() - createdDate.getTime(); | |
Calendar cal = Calendar.getInstance(); | |
cal.setTimeInMillis(difference); | |
if(cal.get(Calendar.YEAR) - 1970 == 0){ | |
if(cal.get(Calendar.MONTH) == 0){ | |
if(cal.get(Calendar.DAY_OF_MONTH) - 1 == 0){ | |
//the following line has hardcoded! | |
if(cal.get(Calendar.HOUR_OF_DAY) - getTimeOffset() - 1 == 0){ | |
if (cal.get(Calendar.MINUTE) == 0){ | |
return "right now"; | |
} else { | |
if (cal.get(Calendar.MINUTE) == 1) { | |
return cal.get(Calendar.MINUTE) + " minute ago"; | |
} else return cal.get(Calendar.MINUTE) + " minutes ago"; | |
} | |
} else { | |
//the following line has hardcoded! | |
if (cal.get(Calendar.HOUR_OF_DAY) - getTimeOffset() - 1 == 1) { | |
//the following line has hardcoded! | |
return cal.get(Calendar.HOUR_OF_DAY) - getTimeOffset() - 1 + " hour ago"; | |
} else return cal.get(Calendar.HOUR_OF_DAY) - getTimeOffset() - 1 + " hours ago"; | |
} | |
} else { | |
if (cal.get(Calendar.DAY_OF_MONTH) - 1 <= 7){ | |
if (cal.get(Calendar.DAY_OF_MONTH) - 1 == 1) { | |
return cal.get(Calendar.DAY_OF_MONTH) - 1 + " day ago"; | |
} else return cal.get(Calendar.DAY_OF_MONTH) - 1 + " days ago"; | |
} else { | |
return DateTimeConverter.getDate(_date); | |
} | |
} | |
} else { | |
return DateTimeConverter.getDate(_date); | |
} | |
} else { | |
return DateTimeConverter.getDate(_date); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment