Reputation: 31
I try to make looping with format Time/Date, but i have stuck to makeit
So i want to loop year, from now(2019 to 5 years before).
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()
}
Actualy i expect output like this: 2019 2018 2017 2016 2015 2014
Upvotes: 0
Views: 410
Reputation: 31
My Logic is low... I just understood now, this just be simple like this:
int tahun = 2019;
int hitung = tahun - 5;
for (int i = tahun; i >= hitung; i--) {
system.out.println(i)
}
Now i just need to get Years from Date.utils
Upvotes: 0
Reputation: 550
Try this one:
LocalDate date = LocalDate.now();
int yearNow = date.getYear();
int minYear = yearNow - 5;
while(yearNow >= minYear) {
System.out.println(yearNow--);
}
Upvotes: 0
Reputation: 4574
Using Calendar :
Calendar calendar = Calendar.getInstance();
for (int i = 0; i <= 5; i++) {
System.out.println(calendar.get(Calendar.YEAR) - i);
}
Upvotes: 0
Reputation: 19926
From the documentation of 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.
So you'd have to add 1900
to get the correct year out (Next to the flaw @BorisTheSpider pointed out in his comment). But there is a better way, using the new java.time
api which replaces the old Date
api:
LocalDate d = LocalDate.now();
for (int i = 0; i <= 5; i++) {
System.out.println(d.getYear());
d = d.minusYears(1);
}
Which prints:
2019
2018
2017
2016
2015
2014
Upvotes: 4