-1

可能重复:
如何计算 Java 中的时间跨度并格式化输出?

是否有一个简单的函数将时间范围格式化为字符串?目前我可以生成这样的输出:

“81天”

final Calendar today = Calendar.getInstance();
int today_day = today.get(Calendar.DAY_OF_YEAR);

final Calendar startCal = Calendar.getInstance();
startCal.add(Calendar.Day_OF_YEAR,81);  
int start_day = startCal.get(Calendar.DAY_OF_YEAR);

 int dif= start_day-today_day;
 if (dif >1){
   str = "in "+dif+" days";
 }

但我希望它是

“2个月零20天”

4

1 回答 1

-1

我建议您使用日期对象:

Date startDay = new Date(); //today
Date targetDay = new Date();
targetDay.setDate(startDay.getDate() + 81);
Date difference = new Date(startDay.getTime() - targetDay.getTime());
// you may format as you want i.e difference.getMonth()
String differenceDateString = difference.toString(); 

CalendargetTime方法也返回Date对象。

于 2012-09-21T12:09:51.550 回答