0

我需要得到一个季度的统计数据。

示例:今天是 2018 年 2 月 10,我需要检索 2017 年 12 月 1至 31、2018 年 1 月 1至 30以及 2 月 1至当前日期的数据。

如何使用 Java 实现这一点Date

4

3 回答 3

2
于 2018-03-13T13:17:32.787 回答
1

尝试这样的事情:

// Get current date
Calendar start;
start = Calendar.getInstance();

// Go to beginning of month
start.set(Calendar.DAY_OF_MONTH, 1);
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);

// Go 2 months back
my_date.add(Calendar.MONTH, -2);

// Get end of same month
Calendar end;
end = start.clone();
end.add(Calendar.MONTH, 1);
end.add(Calendar.DAY_OF_MONTH, -1);

然后,在其他月份做类似的事情

于 2018-03-13T13:05:03.903 回答
1

您可以使用Java 8 的 java.time类(或Java <= 7 的三个 backport)。

如果您只使用日/月/年而不关心小时和时区,那么最好使用的类是LocalDate. 创建特定日期很容易:

// February 10th 2018
LocalDate current = LocalDate.of(2018, 2, 10);

或者您可以致电LocalDate.now()获取当前日期。

然后,要到 2017 年 12 月 1,您必须减去 2 个月(2 月之前的 2 个月是 12 月)并将日期设置为 1:

// start is December 1st 2017
LocalDate start = current
    // 2 months ago = December
    .minusMonths(2)
    // change day of month to 1st
    .withDayOfMonth(1);

然后你可以从 12 月 1日到 2 月 10循环:

LocalDate date = start;
while (date.isBefore(current)) {
    // do whatever you need with the date

    // go to the next day
    date = date.plusDays(1);
}

请注意,它plusDays返回一个新对象,所以我必须将它分配给同一个变量,否则它不会被更改。

我还使用isBefore了 ,它不包括循环中的当前日期 - 它将在 2 月 9停止。如果要包括 2 月 10,请将条件更改为if (! date.isAfter(current))

于 2018-03-13T13:20:11.803 回答