Is there something like TimeSpan in Android development?

I need to know if there is something like a difference in the development of Android?

There is something like in C #, and I like to use it in two ways:

  • create a time interval, and then add, for example. minutes and then display the entire range
  • create a time interval between two DateTime (which is equivalent for DateTime in android?)
+5
source share
6 answers
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();

} 

transfer date and time in seconds, it will return the changed time ...

+5
source

Unfortunately, there is no class TimeSpanthat is still available in Java, but you can achieve this with a 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;
+3
source

Android has DateUtils, the "formatElapsedTime" method does what you need if you give it the correct input.

+2
source

You can easily get "TimeSpan" in milliseconds. To convert milliseconds to formatted, you can do a small quick and elegant calculation in your function, for example,

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);
}
+1
source

Dates in Java are inconvenient. Take a look at https://github.com/dlew/joda-time-android

0
source

All Articles