How can I get the last 7 days from the current day in ascending order in java?

I use the 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 gives the following result:

 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, this 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?

+5
source share
9 answers

I would simplify your method a little if you need this output, you do not need to create an array of String[] , or twice in a loop, you can achieve the same with a single for-loop , one Calendar and 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 

IDEONE Working Demo

+7
source

Just follow the return path:

  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(int i = (days.length-1); i >= 0; i--){ System.out.println(days[i]); } 

This is the conclusion:

 2016-04-09 2016-04-10 2016-04-11 2016-04-12 2016-04-13 2016-04-14 
+2
source

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); 

He 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 a collection, you need to use a collector.

In your example, you print 6 days, so I'm not right now if this is your mistake, or you need 6 days instead of 7.

+2
source

Collections.sort

You can use the Collections.sort method. This is a static method. You give him a list and a comparator. It uses a modified merge algorithm over the list. This is why you should pass it to a comparator to compare pairs. This was also answered.

Sort objects in ArrayList by date?

+1
source

Here is a suggestion:

 String[] days = new String[6]; for (int i = 0; i < days.length; i++) { days[i] = LocalDate.now().minusDays(days.length - i - 1).toString(); } for (String x : days) { System.out.println(x); } 

And perhaps even clearer using the list:

 List<String> days = new ArrayList<> (); LocalDate now = LocalDate.now(); for (LocalDate d = now.minusDays(5); !d.isAfter(now); d = d.plusDays(1)) { days.add(d.toString()); } for (String x : days) { System.out.println(x); } 
+1
source

Try the following:

Change days to a Date array, and then convert it to a list and sort the list using Collections.sort(list);

 public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "); Calendar cal = Calendar.getInstance(); Date date=cal.getTime(); Date[] days = new Date[6]; days[0]= date; for(int i = 1; i< 6; i++){ cal.add(Calendar.DAY_OF_MONTH,-1); date=cal.getTime(); days[i]=date; } List<Date> list = Arrays.asList(days); Collections.sort(list); for(Date x: days){ System.out.println(sdf.format(x)); } } 
0
source

Instead of going forward, you can try using a loop going backward. Replace the following two lines of your code:

 days[0] = sdf.format(date); for(int i = 1; i < 6; i++){ 

with:

 days[days.length - 1] = sdf.format(date); for(int i = days.length - 2; i >= 0; i--){ 

OUTPUT:

 2016-04-14 2016-04-13 2016-04-12 2016-04-11 2016-04-10 2016-04-09 

EDIT: Better yet, use the Jordi Castilla solution .

0
source

If the number of days is constant, you can simply start filling the array from the end (of course, after highlighting the table: new String[DAYS] ):

 private static final DAYS = 6; //... for(int i = DAYS; i >= 0; i--){ cal.add(Calendar.DAY_OF_MONTH,-1); date = cal.getTime(); days[i] = sdf.format(date); } 
0
source

Other answers use old deprecated classes or are too complex.

java.time

The old date and time classes have been replaced by the java.time platform built into Java 8 and later, with back ports on Java 6 and 7 and Android. Old classes turned out to be poorly designed, confusing, and unpleasant. Avoid them.

LocalDate

Among the new LocalDate classes is the date value only with no time and no time zone. Until saved, a time zone is required to determine today. There are new sunrises in the east, so the date can vary between time zones, tomorrow in Paris and yesterday in Montreal.

 ZoneId zoneId = ZoneId.of( "America/Montreal" ); LocalDate today = LocalDate.now( zoneId ); 

You can add and subtract. We want to return for a week, so we subtract the week.

 LocalDate limit = today.minusWeeks( 1 ); 

Loops a day until we reach the limit. Collect each date as it grows.

A List - an ordered collection, sequence. The ArrayList class is a suitable implementation for our needs.

 List< LocalDate > list = new ArrayList<>(); 

A loop, while each reduced date will still be later than our breakpoint (a week ago).

 LocalDate localDate = today; while ( localDate.isAfter( limit ) ) { list.add( localDate ); // Setup next loop. localDate = localDate.minusDays( 1 ); } 

Sorting

Finally, sort your list in whatever direction you want.

The Collections class (note the plural 'in name) provides many useful methods. Call sort for a natural order. Call reverse for the opposite of the natural order.

 Collections.sort( list ); Collections.reverse( list ); 
0
source

Source: https://habr.com/ru/post/1247118/


All Articles