Last active
April 14, 2016 19:56
-
-
Save novanto/04acc8e5cd93318b2b55bf8cf4299375 to your computer and use it in GitHub Desktop.
Time helper for parsing YYYY-MM-dd
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
public class TimeHelper { | |
public String timeParser(String timestamp){ | |
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |
Date date = new Date(); | |
try{ | |
Date date2 = sdf.parse(timestamp); | |
long currentTimestamp = date.getTime(); | |
long targetTimestamp = date2.getTime(); | |
long res = currentTimestamp - targetTimestamp; | |
long diffSeconds = res / 1000 % 60; | |
long diffMinutes = res / (60 * 1000) % 60; | |
long diffHours = res / (60 * 60 * 1000); | |
int diffInDays = (int) ((res) / (1000 * 60 * 60 * 24)); | |
String dateData = timestamp.split(" ")[0]; | |
String day = dateData.split("-")[2]; | |
int monthnum = Integer.parseInt(dateData.split("-")[1]); | |
String month = switchMonth(monthnum); | |
String year = dateData.split("-")[0]; | |
String dmyDate = (day+" "+month+" "+year); | |
if (diffInDays > 2) { | |
return dmyDate; | |
} else if (diffHours >= 24 && diffInDays <= 2) { | |
return diffInDays+" hari lalu"; | |
} else if (diffHours >= 1 && diffHours < 24) { | |
return diffHours+" jam lalu"; | |
} else if (diffHours < 1 && diffMinutes >= 1 && diffMinutes <= 59) { | |
return diffMinutes+" menit lalu"; | |
} else if (diffMinutes < 1 && diffSeconds >= 1 && diffSeconds <= 59) { | |
return diffSeconds+" detik lalu"; | |
} else { | |
return dmyDate; | |
} | |
} catch(Exception e) { | |
LogUtils.LOGE("error date parse", e.getMessage()); | |
return ""; | |
} | |
} | |
public String switchMonth(int monthnum){ | |
switch(monthnum){ | |
case 1: return "Januari"; | |
case 2: return "Februari"; | |
case 3: return "Maret"; | |
case 4: return "April"; | |
case 5: return "Mei"; | |
case 6: return "Juni"; | |
case 7: return "Juli"; | |
case 8: return "Agustus"; | |
case 9: return "September"; | |
case 10: return "Oktober"; | |
case 11: return "November"; | |
case 12: return "Desember"; | |
default: return "Januari"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment