由昨天下班前的一段对话引出:
“A:折腾了一天,总算吧时间间距n个月算法写好了”
“B:出于经验,calendar类或者是common.lang肯定有现成函数”
直接贴代码。
System.out.println(DurationFormatUtils.formatPeriod(new Date("2012/05/05").getTime(), new Date("2013/08/07").getTime(), "y-M-d"));
函数来自common.lang包,2.x-3.x都有实现。 可以将日期间距按指定的字段需求做计算。
org.apache.commons.lang3.time.DurationFormatUtils Duration formatting utilities and constants. The following table describes the tokens used in the pattern language for formatting. character duration element y years M months d days H hours m minutes s seconds S milliseconds Since: 2.1 Version: $Id: DurationFormatUtils.java 1144993 2011-07-11 00:51:16Z ggregory $
这里的经验是,被提过10000次的需求。。肯定有现成解决方案,不要重复发明基础轮子。 但是基于这个函数,到真正的业务需求(比如2个月3天,在业务里面可能归成3个月大小),做一些小逻辑封装即可。