问题
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.
回答1:
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.
回答2:
If you're using java.util.Date;
you're gonna have to use an intermediate variable. you can convert your dates to long
values and subtract those and then convert your long back to a date.
long diff = new Date().getTime() - new Date(milliseconds).getTime();
Date dateDiff = new Date(diff);
But you should be warned that it doesn't take daylight savings and whatever else variables into account. if you're that scrupulous, you might be indulged with this replacement date class. It has the functionality you seek.
回答3:
I use this code to get difference of two date.
public void getTimeDifference(Date endDate,Date startDate) {
Date diff = new Date(endDate.getTime() - startDate.getTime());
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTime(diff);
int day=calendar.get(Calendar.DAY_OF_MONTH);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
}
}
来源:https://stackoverflow.com/questions/13216263/difference-between-two-datetime-formats-in-android