Search code examples
javamathtimemilliseconds

milliseconds to days


i did some research, but still can't find how to get the days... Here is what I got:

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);
int days = ????? ;

Please help, I suck at math, thank's.


Solution

  • If you don't have another time interval bigger than days:

    int days = (int) (milliseconds / (1000*60*60*24));
    

    If you have weeks too:

    int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
    int weeks = (int) (milliseconds / (1000*60*60*24*7));
    

    It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.