Skip to content Skip to sidebar Skip to footer

Is There Something Like Timespan In Android Development?

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: generate a timespan and then add e.g.

Solution 1:

publiclongaddSeconds(long dt,int sec)//method to add seconds in time  
{

    DateDt=newDate(dt);
    Calendarcal=newGregorianCalendar();

    SimpleDateFormatsdf=newSimpleDateFormat("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...

Solution 2:

Unfortunately, there's no TimeSpan like class yet natively available in Java, but you can achieve this with few lines of code.

CalendarstartDate= getStartDate();
CalendarendDate= getEndDate();

longtotalMillis= endDate.getTimeInMillis() - startDate.getTimeInMillis();
intseconds= (int) (totalMillis / 1000) % 60;
intminutes=  ((int)(totalMillis / 1000) / 60) % 60;
inthours= (int)(totalMillis / 1000) / 3600;

Solution 3:

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

Solution 4:

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,

publicstatic String GetFormattedTimeSpan(finallong 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);
}

Solution 5:

You can use the Calendar class.

http://tutorials.jenkov.com/java-date-time/java-util-calendar.html

Post a Comment for "Is There Something Like Timespan In Android Development?"