I am using following code to get the last 7 days:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String[] days = new String[6];
days[0] = sdf.format(date);
for(int i = 1; i < 6; i++){
cal.add(Calendar.DAY_OF_MONTH, -1);
date = cal.getTime();
days[i] = sdf.format(date);
}
for(String x: days){
System.out.println(x);
}
And this is giving the following output:
2016-04-14
2016-04-13
2016-04-12
2016-04-11
2016-04-10
2016-04-09
But I want this instead:
2016-04-09
2016-04-10
2016-04-11
2016-04-12
2016-04-13
2016-04-14
If I use the following line below the code it will give me the correct order:
List<String> list = Arrays.asList(days);
Collections.reverse(list);
days = (String[]) list.toArray();
for(String x: days){
System.out.println(x);
}
But is there any other way to get the last 7 days in ascending order in one shot?
Adding Days to the given Date using Calendar class Add the given date to the calendar by using setTime() method of calendar class. Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added.
LocalDate class and its plusDays() method to increment the date by one day.
The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31. This instance is immutable and unaffected by this method call.
I would simplify your method a bit, if you want this output you don't need to create an String[]
array, either loop twice, you can achieve same with a single for-loop
, one Calendar
and the SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");
Calendar cal = Calendar.getInstance();
// get starting date
cal.add(Calendar.DAY_OF_YEAR, -6);
// loop adding one day in each iteration
for(int i = 0; i< 6; i++){
cal.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(sdf.format(cal.getTime()));
}
OUTPUT:
2016-04-09
2016-04-10
2016-04-11
2016-04-12
2016-04-13
2016-04-14
Working IDEONE demo
Using java8 and joda you can write something like:
LocalDate weekBeforeToday = LocalDate.now().minusDays(7);
IntStream.rangeClosed(1, 7)
.mapToObj(weekBeforeToday::plusDays)
.forEach(System.out::println);
It prints:
2016-04-08
2016-04-09
2016-04-10
2016-04-11
2016-04-12
2016-04-13
2016-04-14
If you need collection you have to use collector.
In your example you're printing 6 days so I don't now if it's your mistake or you need 6 days instead of 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With