英文:
Split a couple of dates in smaller chunks
问题
I have 2 dates:
public static Date getStartDate() {
Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, 2020);
instance.set(Calendar.MONTH, 7);
instance.set(Calendar.DAY_OF_MONTH, 7);
instance.set(Calendar.HOUR_OF_DAY, 9);
instance.set(Calendar.MINUTE, 50);
return instance.getTime();
}
public static Date getEndDate() {
Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, 2020);
instance.set(Calendar.MONTH, 7);
instance.set(Calendar.DAY_OF_MONTH, 11);
instance.set(Calendar.HOUR_OF_DAY, 9);
instance.set(Calendar.MINUTE, 46);
return instance.getTime();
}
I have the limitation that if the start and end times have a duration of more than an hour, the process will fail. So, if I have a large time frame like the previous one, I need to split it into smaller chunks, each not exceeding one hour.
Is there an API that can divide the given start and end times into a list of smaller periods?
Thanks.
英文:
I have 2 dates:
public static Date getStartDate() {
Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, 2020);
instance.set(Calendar.MONTH, 7);
instance.set(Calendar.DAY_OF_MONTH, 7);
instance.set(Calendar.HOUR_OF_DAY, 9);
instance.set(Calendar.MINUTE, 50);
return instance.getTime();
}
public static Date getEndDate() {
Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, 2020);
instance.set(Calendar.MONTH, 7);
instance.set(Calendar.DAY_OF_MONTH, 11);
instance.set(Calendar.HOUR_OF_DAY, 9);
instance.set(Calendar.MINUTE, 46);
return instance.getTime();
}
I have the limitation that if start and end is more than an hour the process will fail, so if i have a big time frame as the previous one i need to split it in smaller chunks not bigger than an hour.
Is there an api that can divide the given start and end time to a list of smaller periods ?
Thanks.
答案1
得分: 4
这没有内置的方法,但你可以轻松自己编写。这会构建一个由java.time.Instant
对象组成的列表,它们相隔一小时,从你的起始日期开始,结束于你的结束日期之前:
Instant start = getStartDate().toInstant();
Instant endExclusive = getEndDate().toInstant();
ArrayList<Instant> chunks = new ArrayList<>();
Instant chunkStart = start;
while (chunkStart.isBefore(endExclusive)) {
chunks.add(chunkStart);
chunkStart = chunkStart.plus(1, ChronoUnit.HOURS);
}
注意,这里的end
日期是不包括的:它从未添加到chunks
列表中。
英文:
There is no built-in method, but you can easily write yourself. This constructs a list of java.time.Instant
objects that are one hour apart, starting from your start date and ending just before your end date:
Instant start = getStartDate().toInstant();
Instant endExclusive = getEndDate().toInstant();
ArrayList<Instant> chunks = new ArrayList<>();
Instant chunkStart = start;
while (chunkStart.isBefore(endExclusive)) {
chunks.add(chunkStart);
chunkStart = chunkStart.plus(1, ChronoUnit.HOURS);
}
Note that the end
date here is exclusive: it's never added to the chunks
list.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论