gpt4 book ai didi

Java 从现在到向后循环年份

转载 作者:行者123 更新时间:2023-12-01 17:46:20 25 4
gpt4 key购买 nike

我尝试使用时间/日期格式进行循环,但我坚持使用 makeit

所以我想循环年份,从现在开始(2019 年到 5 年前)。

Date d = new Date();
long tahun = d.getYear();
long hitung = tahun - 5;

for (long i = tahun; i >= hitung; i--) {
d = new Date(tahun);
d.getYear()
}

实际上我期望这样的输出:2019年2018年2017年2016年2015年2014年

最佳答案

摘自Date#getYear()的文档:

Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

因此,您必须添加 1900 才能获得正确的年份(@BorisTheSpider 在他的评论中指出的缺陷旁边)。但有更好的方法,使用新的 java.time api 替换旧的 Date api:

LocalDate d = LocalDate.now();
for (int i = 0; i <= 5; i++) {
System.out.println(d.getYear());
d = d.minusYears(1);
}

打印内容:

2019
2018
2017
2016
2015
2014

关于Java 从现在到向后循环年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54761188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com