I need to know if there is something like a timespan in android development?
in C# there is something like and I like to use it in two ways:
Dates in Java are awkward. Have a look at https://github.com/dlew/joda-time-android
Unfortunately, there's no TimeSpan
like class yet natively available in Java, but you can achieve this with few lines of code.
Calendar startDate = getStartDate();
Calendar endDate = getEndDate();
long totalMillis = endDate.getTimeInMillis() - startDate.getTimeInMillis();
int seconds = (int) (totalMillis / 1000) % 60;
int minutes = ((int)(totalMillis / 1000) / 60) % 60;
int hours = (int)(totalMillis / 1000) / 3600;
Android has DateUtils, the method "formatElapsedTime" does what you need if you give it the right input.
You can easily get the "TimeSpan" in milliseconds. To convert milliseconds to a formatted one, you can do a little fast and elegant calculation in your function like this,
public static String GetFormattedTimeSpan(final long ms) {
long x = ms / 1000;
long seconds = x % 60;
x /= 60;
long minutes = x % 60;
x /= 60;
long hours = x % 24;
x /= 24;
long days = x;
return String.format("%d days %d hours %d minutes %d seconds", days, hours, minutes, seconds);
}
public long addSeconds(long dt,int sec) //method to add seconds in time
{
Date Dt = new Date(dt);
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
sdf.setCalendar(cal);
cal.setTimeInMillis(Dt.getTime());
cal.add(Calendar.SECOND, sec);
return cal.getTime().getTime();
}
pass date and time in sec, it will return modified time...
You can use the Calendar class.
http://tutorials.jenkov.com/java-date-time/java-util-calendar.html