Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Milliseconds in Year

Tags:

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?

like image 804
Kevin Bowersox Avatar asked Feb 04 '12 15:02

Kevin Bowersox


People also ask

How do you convert milliseconds to dates?

This is the number of seconds since the 1970 epoch. To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.

How do you represent milliseconds in Java?

The millis() method of Clock class returns the current instant of the clock in milliseconds. A millisecond instant is measured from 1970-01-01T00:00Z (UTC) to the current time. This method does the same work as System. currentTimeMillis() method.

Does Java Util date have milliseconds?

Actually java. util. Date is internally specified in milliseconds from epoch. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and Date provides constructor which can be used to create Date from milliseconds.


Video Answer


2 Answers

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;
like image 100
ruakh Avatar answered Oct 07 '22 20:10

ruakh


If on android, I suggest:

android.text.format.DateUtils

DateUtils.SECOND_IN_MILLIS
DateUtils.MINUTE_IN_MILLIS
DateUtils.HOUR_IN_MILLIS
DateUtils.DAY_IN_MILLIS
DateUtils.WEEK_IN_MILLIS
DateUtils.YEAR_IN_MILLIS
like image 25
Oded Breiner Avatar answered Oct 07 '22 21:10

Oded Breiner