Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing a Joda Time Period into intervals of desired size?

Tags:

java

jodatime

I have a "period" (P) of time that is represented by a start time (S) and an end time (E). I want to divide P into C chunks of size D. That is,

P = C * D + R, where R is the remainder or leftover time.

eg.

S = NOW, E = 10 sec after NOW, D = 3 sec.
Therefore, P = 10 sec, C = 3, R = 1 sec. 

I want to store and display all the chunks C with their start times, end times and sizes. Finally, I want to store and display the remainder. How do I do this using Joda Time ?

Does the API provide simple methods and classes to do this or I will have to figure a way out ?

This question is a small part of another question I have posted here

like image 961
Jedi Knight Avatar asked Mar 12 '13 10:03

Jedi Knight


1 Answers

I'm not sure whether this code is what you're looking for but it might get you on the right track.

I assumed you have two DateTimes to represent the start and end dates, because a Joda-Time Period represents a period of time like 1 month or 2 weeks. It doesn't have a specific start or end like, for example an Interval which represents a slice of time between two instants.

import java.util.*;
import org.joda.time.*;

class Test {
    public static void main(String... args) {
        DateTime now = new DateTime();
        List<Interval> list = splitDuration(now, now.plusSeconds(10), 3, 3 * 1000);

        for(Interval i : list) {
            System.out.println(i.getStart() + " - " +
                               i.getEnd() + " - " +
                               i.toDurationMillis());
        }
    }

    static List<Interval> splitDuration(DateTime start, DateTime end, long chunkAmount, long chunkSize) {
        long millis = start.getMillis();
        List<Interval> list = new ArrayList<Interval>();

        for(int i = 0; i < chunkAmount; ++i) {
            list.add(new Interval(millis, millis += chunkSize));
        }

        list.add(new Interval(millis, end.getMillis()));
        return list;
    }
}

Output in my case:

2013-03-12T12:29:01.781+01:00 - 2013-03-12T12:29:04.781+01:00 - 3000
2013-03-12T12:29:04.781+01:00 - 2013-03-12T12:29:07.781+01:00 - 3000
2013-03-12T12:29:07.781+01:00 - 2013-03-12T12:29:10.781+01:00 - 3000
2013-03-12T12:29:10.781+01:00 - 2013-03-12T12:29:11.781+01:00 - 1000
like image 121
Daan Avatar answered Sep 28 '22 17:09

Daan