java 毫秒数比较,年份中的Java毫秒数

I am doing some date calculations in Java using milliseconds and noticing an issue with the following:

private static final int MILLIS_IN_SECOND = 1000;

private static final int SECONDS_IN_MINUTE = 60;

private static final int MINUTES_IN_HOUR = 60;

private static final int HOURS_IN_DAY = 24;

private static final int DAYS_IN_YEAR = 365; //I know this value is more like 365.24...

private static final long MILLISECONDS_IN_YEAR = MILLIS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_YEAR;

System.out.println(MILLISECONDS_IN_YEAR); //Returns 1471228928

I know that that 1 Year is roughly = 31,556,952,000 Milliseconds, so my multiplication is off somehow.

Can anyone point out what I am doing wrong? Should I be using a long?

解决方案

Should I be using a long?

Yes. The problem is that, since MILLIS_IN_SECOND and so on are all ints, when you multiply them you get an int. You're converting that int to a long, but only after the int multiplication has already resulted in the wrong answer.

To fix this, you can cast the first one to a long:

private static final long MILLISECONDS_IN_YEAR =

(long)MILLIS_IN_SECOND * SECONDS_IN_MINUTE * MINUTES_IN_HOUR

* HOURS_IN_DAY * DAYS_IN_YEAR;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值