Search code examples
javadatetimeroundingepoch

Round date long value


In my Java project I used date in long and for example it is 12136219 and by creating Date object as below:

long time = 12136219;
Date date = new Date(time);

and it represent date as Thu Jan 01 04:22:16 CET 1970. How can I round date (in long representation) to minutes ?

For example I want achieve Thu Jan 01 04:22:00 CET 1970 if the seconds are <30 and Thu Jan 01 04:23:00 CET 1970 if the seconds are >=30 but I want round this long time = 12136219 representation. Any idea?


Solution

  • Since time is "milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT" You could calculate the seconds like this:

    secondsInMillis = time % (60 * 1000) //get remainder (modulo): seconds * milliseconds
    if (secondsInMillis < 30000) {
      time -= secondsInMillis; //round down
    } else {
      time += (60000 - secondsInMillis); // round up
    }