将整数转换为 Java 中的日期

Convert Integer To Date in Java

我有整数 a = 30;

如何转换每个月的日期 30。

例子

整数a = 25; 25/01/2021 25/02/2021 25/03/2021

整数a = 10; 10/01/2021 10/02/2021 10/03/2021

您可以使用LocalDate#of and LocalDate#plusMonths

int day = 31;
int months = 3;

LocalDate firstDate = LocalDate.of(2021, 1, day);

List<LocalDate> dates = IntStream.range(0, months)
        .mapToObj(firstDate::plusMonths)
        .collect(Collectors.toList());

这将输出这些日期:

2021-01-31
2021-02-28
2021-03-31

您可以创建一个循环 运行 12 次(每个月一次)。从月份 1 和指定的日期开始。在每次迭代中,打印日期,并在下一次迭代中将月份递增 1

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        int x = 10;
        LocalDate start = LocalDate.now().withMonth(1).withDayOfMonth(x);
        for (int i = 1; i <= 12; i++, start = start.plusMonths(1)) {
            System.out.println(start.format(DateTimeFormatter.ofPattern("dd/MM/uuuu")));
        }
    }
}

输出:

10/01/2021
10/02/2021
10/03/2021
10/04/2021
10/05/2021
10/06/2021
10/07/2021
10/08/2021
10/09/2021
10/10/2021
10/11/2021
10/12/2021

Trail: Date Time.

了解有关日期时间 API 的更多信息