`
sw1982
  • 浏览: 504716 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java怎么计算两个日期间隔的天,月,年

 
阅读更多

 

由昨天下班前的一段对话引出:

“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个月大小),做一些小逻辑封装即可。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics