Skip to content

Instantly share code, notes, and snippets.

@Antarix
Last active November 24, 2016 09:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Antarix/9a15ec5220abc40085e5 to your computer and use it in GitHub Desktop.
Save Antarix/9a15ec5220abc40085e5 to your computer and use it in GitHub Desktop.
Get Elapsed time from date
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.text.format.DateUtils;
public class TimeUtils {
public static final String DD_MM_YY_HH_MM = "dd-MMM-yy h:mm";
public static final String HH_MM = "h:mm";
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String getElapsedTime(long duration) {
Calendar cal = Calendar.getInstance();
duration = cal.getTimeInMillis()-duration;
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static String getFormatedDate(String dateTime, String formatType) {
long millisec = Long.parseLong(dateTime);
Date now = new Date(millisec);
// String formatType = "MMM d, ''yy h:mm a";
SimpleDateFormat format = new SimpleDateFormat(formatType,
Locale.ENGLISH);
return format.format(now);
}
public static String getElapsedDateTime(long time){
Calendar cal = Calendar.getInstance();
return DateUtils.getRelativeTimeSpanString(time, cal.getTimeInMillis(), DateUtils.FORMAT_ABBREV_RELATIVE).toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment