Search code examples
androiddatetime-formatandroid-datepicker

Difference between two datetime formats in android?


As i am new to android development I am unable to find code for calculating the difference between two datetime formats. My question is.

I am using webservice in my project where i am getting datetime response as follows..

 starttime  :- [2012-11-04 10:00:00]
 endtime    :- [2012-11-04 12:00:00]

Here i want to display on screen as

   Today Timings  :-  2012-11-04   2 hours

Means need to calculate the difference between two dates and need to display the time difference on screen.

Can anyone please help me with this.


Solution

  • Given you know the exact format in which you are getting the date-time object, you could use the SimpleDateFormat class in Android which allows you to parse a string as a date given the format of the date expressed in the string. For your question:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startTime = sdf.parse(<startTime/endTime String>, 0);
    

    Similarly parse your endtime, and then the difference can be obtained using getTime() of the individual objects.

    long diff = endTime.getTime() - startTime.getTime()
    

    Then it's as simple as converting the difference to hours using:

    int hours = (int)(diff/(60*60*1000));
    

    Hope that helps.