Last active
October 29, 2016 01:58
-
-
Save AmitGoenka/21cba724311ee297ed5e69b8fa26c9ca to your computer and use it in GitHub Desktop.
Time Duration Formatting
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
package org.agoenka.tweeterjam.utils; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.Calendar; | |
import java.util.Locale; | |
/** | |
* Full credit goes to : https://github.com/ewilden/TimeFormatter | |
*/ | |
public class DateUtils { | |
public static final String TWITTER_FORMAT = "EEE MMM dd HH:mm:ss ZZZZZ yyyy"; //"Mon Apr 01 21:16:23 +0000 2014" | |
public static String getDuration(String date, String format) { | |
long time = getTime(date, format); | |
long diff = (System.currentTimeMillis() - time) / 1000; | |
if (diff < 5) | |
return "Just now"; | |
else if (diff < 60) | |
return String.format(Locale.ENGLISH, "%ds", diff); | |
else if (diff < 60 * 60) | |
return String.format(Locale.ENGLISH, "%dm", diff / 60); | |
else if (diff < 60 * 60 * 24) | |
return String.format(Locale.ENGLISH, "%dh", diff / (60 * 60)); | |
else if (diff < 60 * 60 * 24 * 30) | |
return String.format(Locale.ENGLISH, "%dd", diff / (60 * 60 * 24)); | |
else { | |
Calendar now = Calendar.getInstance(); | |
Calendar then = getCalendar(time); | |
if (now.get(Calendar.YEAR) == then.get(Calendar.YEAR)) { | |
return String.valueOf(then.get(Calendar.DAY_OF_MONTH)) + " " | |
+ then.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()); | |
} else { | |
return String.valueOf(then.get(Calendar.DAY_OF_MONTH)) + " " | |
+ then.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()) + " " | |
+ String.valueOf(then.get(Calendar.YEAR) - 2000); | |
} | |
} | |
} | |
private static long getTime(String date, String format) { | |
try { | |
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault()); | |
sdf.setLenient(true); | |
return sdf.parse(date).getTime(); | |
} catch (ParseException e) { | |
e.printStackTrace(); | |
return 0; | |
} | |
} | |
private static Calendar getCalendar(long time) { | |
Calendar calendar = Calendar.getInstance(); | |
calendar.setTimeInMillis(time); | |
return calendar; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment