有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:按n个部分拆分日期

我有两个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

然后我需要一个startend之间的Date列表,分成5部分

In simple words (example):

start = 1PM;
end = 5PM;

count = 5;

list = (1PM, 2PM, 3PM, 4PM, 5PM)

我怎样才能做到这一点


共 (1) 个答案

  1. # 1 楼答案

    爪哇。时间

    使用java。时间,现代Java日期和时间API,用于日期和时间工作

    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。时间到了