ACz
ACz

Reputation: 577

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?

Upvotes: 1

Views: 1776

Answers (5)

Ori Marko
Ori Marko

Reputation: 58812

Reset seconds and milliseconds with Calendar.set

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MINUTES, calendar.get(Calendar.SECOND) >= 30 ? 1 : 0)
currentDate = cal.getTimeInMillis();

Sets the given calendar field to the given value. The value is not interpreted by this method regardless of the leniency mode.

Upvotes: 1

Anonymous
Anonymous

Reputation: 86324

Don’t reinvent the wheel. Use java.time.Instant for representing an instant in time:

    Instant i = Instant.ofEpochMilli(time);
    i = i.plusSeconds(30).truncatedTo(ChronoUnit.MINUTES);

Instant doesn’t offer rounding, only truncation. However, adding 30 seconds and then truncating gives you what you want. If you need your milliseconds back, it’s easy:

    time = i.toEpochMilli();
    System.out.println(time);

With the number from your question this prints

12120000

(This is equal to an instant of 1970-01-01T03:22:00Z, or 1970-01-01T04:22+01:00[Europe/Paris] in CET, or the expected rounding down of your 04:22:16 CET.)

PS I am quite convinced that a library like Time4J will offer rounding so you don’t need the trick of adding and truncating. Unfortunately I don’t have the experience to give you the details.

Upvotes: 4

hawxs
hawxs

Reputation: 103

You should do it on the Date object. There is no easy way to calculate it in the time epoch, because of various difficulties including the length of a month (28, 29, 30 or 31).

Upvotes: 0

M. Haverbier
M. Haverbier

Reputation: 383

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
}

Upvotes: 3

Scott Hunter
Scott Hunter

Reputation: 49883

When you create a Date from a long, the long represents the number of milliseconds since Jan 1, 1970. There are 60*1000 milliseconds in a minute. That should be enough information to fashion the rounding algorithm you need.

Upvotes: 3

Related Questions