计算两个时间戳之间的天数的一种比较高效的算法

因为在做hadoop计算的时候需要按照时间来分片,所以需要对long型的时间戳进行Partition,本来想了一下两个时间先归零到当天的0点,然后想减除以24小时就是中间的天数,这个算法没错,但是我没有考虑到时区的问题,归零的算法是(t1-t1%h24)t是时间戳,h表示一小时的毫秒数,这样归零其实是格林威治时间的归零,在我们这边正好的8点钟,这样就会把两天的数据并到一个分区里面,网上也有做法是

new Long((dateformat.parse(dateformat.format(new Date(curDay))).getTime()-dateformat.parse(dateformat.format(new Date(t1))).getTime())/(1000 * 60 * 60 * 24)).intValue();

但是这种做法肯定很慢而却占用内存,对于每天原始数据有100多个G的文件进行分区这个肯定不行,于是继续改我的归零算法,最后就改成下面的鸟样

private static void test8() throws Exception{
final DateFormat dateformat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
long h8 = 1000 * 60 * 60 *8;
long h16 = h8*2;
long curDay = System.currentTimeMillis();//此处+ut8是因为可以减少在分区的时候做一次减法
long h24 = h8*3;
curDay = curDay - curDay % h24 + (curDay % h24>=h16?h24:0);
System.out.println(dateformat.format(new Date(curDay)));

long t1 = 1368892799999L;
long m = t1%h24;
long i = (curDay-(t1-m+(m>=h16?h24:0)))/h24;
System.out.println(i);
t1 = 1368892799999L-h24+1;
i = (curDay-(t1-m+(m>=h16?h24:0)))/h24;
System.out.println(i);
t1 = 1368892800000L;
i = (curDay-(t1-m+(m>=h16?h24:0)))/h24;
System.out.println(i);
long d1 = System.currentTimeMillis();
for(int a=0;a<1000;a++){
i=new Long((dateformat.parse(dateformat.format(new Date(curDay))).getTime()-dateformat.parse(dateformat.format(new Date(t1))).getTime())/(1000 * 60 * 60 * 24)).intValue();
System.out.println(i);
}
long d2 = System.currentTimeMillis();
for(int a=0;a<1000;a++){
m = t1%h24;
i = (curDay-(t1-m+(m>=h16?h24:0)))/h24;
System.out.println(i);
}
long d3 = System.currentTimeMillis();
System.out.println(d2-d1);
System.out.println(d3-d2);
}


上面是我的测试代码,懒得解释,也很简单,但确效率至少在100倍以上,拿出来呗大家copy用,呵呵
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值