将Joda时间段划分为所需大小的间隔? [英] Dividing a Joda Time Period into intervals of desired size?
问题描述
我有一个期间"(P),由开始时间(S)和结束时间(E)表示. 我想将P分成大小为D的C块.
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,其中R为剩余时间或剩余时间.
P = C * D + R, where R is the remainder or leftover time.
例如
S = NOW, E = 10 sec after NOW, D = 3 sec.
Therefore, P = 10 sec, C = 3, R = 1 sec.
我想存储和显示所有块C及其开始时间,结束时间和大小. 最后,我要存储并显示其余部分.如何使用Joda Time做到这一点?
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 ?
API是否提供了简单的方法和类来做到这一点,否则我将不得不寻找出路?
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
推荐答案
我不确定这段代码是否正是您想要的,但是它可能会让您走上正确的轨道.
I'm not sure whether this code is what you're looking for but it might get you on the right track.
我假设您有两个DateTimes来表示开始日期和结束日期,因为Joda-Time Period代表一个时间段,例如1个月或2周.它没有特定的开始或结束,例如一个代表两个时刻之间的时间片的时间间隔.
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;
}
}
在我的情况下输出:
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
这篇关于将Joda时间段划分为所需大小的间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!