我有两个Date
格式的yyyy-MM-dd HH:mm:ss.SSS
值。
我有一个动态的int变量,它将由另一个进程更新。
(例如)
Date start = new Date(<some long value>); //2020-01-01 11:12:13.111
Date end = new Date(<some long value>); //2020-01-10 14:15:16.222
int count = 5; //this is dynamic
然后我需要一个Date
和start
之间的end
列表,分为5部分。
In simple words (example):
start = 1PM;
end = 5PM;
count = 5;
list = (1PM, 2PM, 3PM, 4PM, 5PM)
我该如何实现?
答案 0 :(得分:2)
使用现代Java日期和时间API java.time进行日期和时间工作。
在count
等于5的情况下,我知道您想要5次,因此它们之间有4个相等长的间隔。
ZoneId zone = ZoneId.of("Europe/Tirane");
ZonedDateTime start = Instant.ofEpochMilli(1_577_873_533_111L).atZone(zone);
ZonedDateTime end = Instant.ofEpochMilli(1_578_662_116_222L).atZone(zone);
int count = 5;
Duration total = Duration.between(start, end);
Duration each = total.dividedBy(count - 1);
ZonedDateTime current = start;
for (int i = 0; i < count - 1; i++) {
System.out.println(current);
current = current.plus(each);
}
System.out.println(end);
此示例代码段的输出为:
2020-01-01T11:12:13.111+01:00[Europe/Tirane] 2020-01-03T17:57:58.888750+01:00[Europe/Tirane] 2020-01-06T00:43:44.666500+01:00[Europe/Tirane] 2020-01-08T07:29:30.444250+01:00[Europe/Tirane] 2020-01-10T14:15:16.222+01:00[Europe/Tirane]
如果不是欧洲/地拉那,请替换您所需的时区。如果要使用JVM的默认时区,请使用ZoneId.systemDefault()
。
链接: Oracle tutorial: Date Time解释了如何使用java.time。