Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like TimeSpan in android development?

Tags:

android

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:

  1. generate a timespan and then add e.g. minutes and then display the whole span
  2. generate the timespan between two DateTime (what is the equivalent for DateTime in android?)
like image 615
gurehbgui Avatar asked Apr 13 '12 06:04

gurehbgui


3 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();

} 

pass date and time in sec, it will return modified time...

like image 146
Sandeep Avatar answered Oct 21 '22 06:10

Sandeep


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;
like image 32
waqaslam Avatar answered Oct 21 '22 06:10

waqaslam


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

like image 40
Christine Avatar answered Oct 21 '22 07:10

Christine