我正在计算两个日期之间的时差。
Calendar currentDate = Calendar.getInstance();
long currentDateInMillis = currentDate.getTimeInMillis();
//Set Event Date and time
Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
nextDate.set(Calendar.YEAR, 2013);
nextDate.set(Calendar.MONTH, 10); // January is 0, Feb is 1, etc.
nextDate.set(Calendar.DATE, 27);
nextDate.set(Calendar.HOUR_OF_DAY, 23);
nextDate.set(Calendar.MINUTE, 0);
nextDate.set(Calendar.SECOND, 0);
nextDate.set(Calendar.MILLISECOND, 0);
long nextDateInMillis = nextDate.getTimeInMillis();
timeDiff = nextDateInMillis - currentDateInMillis;
timer = new CountDownTimer(timeDiff, 1000)
{
public void onTick(long millisUntilFinished)
{
int totalSeconds = (int) (millisUntilFinished / 1000);
int daysText = (int) (totalSeconds / 86400);
int hoursText = (int) ((totalSeconds % 86400) / 3600);
int minutesText = (int) (((totalSeconds % 86400) % 3600) / 60);
//int secondsText = (int) (((totalSeconds % 86400) % 3600) % 60);
minutes.setText(String.valueOf(minutesText));
hours.setText(String.valueOf(hoursText));
days.setText(String.valueOf(daysText));
}
public void onFinish()
{
}
};
timer.start();
上述效果很好,但它可以提供日,小时和秒。我想让它告诉我几个月。但问题是每个月有不同的天数所以我怎么能找到几个月?
答案 0 :(得分:1)
为什么不使用Joda Time?
例如:
public class DateTimeUtils {
public static void main(String[] args) {
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/11/2014 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void printDifference(Date startDate, Date endDate){
Interval interval =
new Interval(startDate.getTime(), endDate.getTime());
Period period = interval.toPeriod();
System.out.printf(
"%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n",
period.getYears(), period.getMonths(), period.getDays(),
period.getHours(), period.getMinutes(), period.getSeconds());
}
}
只需输入两次,输出就像:
a years, b months, c days, d hours etc...
答案 1 :(得分:1)
我说LotusUNSW的答案几乎就是你所需要的。所以,我只需要添加更多信息......你只需要获取当前时间(或者自从你获得它之后传递它),取倒数时间的毫秒数,将它们一起添加到目标中时间,然后使用Interval找到当前时间和目标时间之间的时间间隔。
使用JodaTime作为LotusUNSW ...
public void onTick(long millisUntilFinished)
{
long currentTime = DateTimeUtils.currentTimeMillis();
Period period = new Interval(currentTime, currentTime +
millisUntilFinished).toPeriod(PeriodType.yearMonthDayTime());
System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n",
period.getYears(), period.getMonths(), period.getDays(),
period.getHours(), period.getMinutes(), period.getSeconds());
}
对于您所在的日期,其输出如下所示:0 years, 0 months, 10 days, 14 hours, 6 minutes, 29 seconds
您可以找到不同的PeriodType
选项here。如果您希望只拥有一种类型的单位,则可以使用PeriodTypes,例如PeriodType.months()
,如果您想要以月为单位的总时间。