简体   繁体   中英

How to get dates for next seven days from calendar java

So, I have an application where user can select a date .

The maximum date that he can select is upto 7 more days from the current date.

Now, I display a calendar for the current month only. If the current date is 30th July then the user must be provided an option to select date upto 6th Aug also I have to handle the case where the year changes ie 30th Dec,15 is the current date and +7 days provide 6th Jan,16.

Below is the code that I am using to get all the days of current month. What should I do to get it work for the above scenario.

Note: I always have the current date available.

Code:

   public class Cals {

        public static void main(String args[])
        {
            Calendar start = Calendar.getInstance();
            start.set(Calendar.DAY_OF_MONTH, Calendar.getInstance()
                    .getActualMinimum(Calendar.DAY_OF_MONTH));
            Calendar end = Calendar.getInstance();
            end.set(Calendar.DAY_OF_MONTH,
                    Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
            Calendar now = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM");

            for (Date dt = start.getTime(); !start.after(end); start.add(
                    Calendar.DATE, 1), dt = start.getTime()) {

                System.out.println(sdf.format(dt));
            }
        }
    }

Current O/p:

Wed 1 Jul
Thu 2 Jul
Fri 3 Jul
Sat 4 Jul
Sun 5 Jul
Mon 6 Jul
Tue 7 Jul
Wed 8 Jul
Thu 9 Jul
Fri 10 Jul
Sat 11 Jul
Sun 12 Jul
Mon 13 Jul
Tue 14 Jul
Wed 15 Jul
Thu 16 Jul
Fri 17 Jul
Sat 18 Jul
Sun 19 Jul
Mon 20 Jul
Tue 21 Jul
Wed 22 Jul
Thu 23 Jul
Fri 24 Jul
Sat 25 Jul
Sun 26 Jul
Mon 27 Jul
Tue 28 Jul
Wed 29 Jul
Thu 30 Jul
Fri 31 Jul

Expected O/p:

Wed 1 Jul
Thu 2 Jul
Fri 3 Jul
Sat 4 Jul
Sun 5 Jul
Mon 6 Jul
Tue 7 Jul
Wed 8 Jul
Thu 9 Jul
Fri 10 Jul
Sat 11 Jul
Sun 12 Jul
Mon 13 Jul
Tue 14 Jul
Wed 15 Jul
Thu 16 Jul
Fri 17 Jul
Sat 18 Jul
Sun 19 Jul
Mon 20 Jul
Tue 21 Jul
Wed 22 Jul
Thu 23 Jul
Fri 24 Jul
Sat 25 Jul
Sun 26 Jul
Mon 27 Jul
Tue 28 Jul
Wed 29 Jul
Thu 30 Jul
Fri 31 Jul
Sat 1 Aug
Sun 2 Aug
Mon 3 Aug
Tue 4 Aug
Wed 5 Aug
Thu 6 Aug

Simply add 7 days to the end Calendar

Calendar end = Calendar.getInstance();
end.set(Calendar.DAY_OF_MONTH,
                Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
end.add(Calendar.DATE, 7);

Calendar will take care of the rollover automtically

New output...

Wed 1 Jul
Thu 2 Jul
Fri 3 Jul
Sat 4 Jul
Sun 5 Jul
Mon 6 Jul
Tue 7 Jul
Wed 8 Jul
Thu 9 Jul
Fri 10 Jul
Sat 11 Jul
Sun 12 Jul
Mon 13 Jul
Tue 14 Jul
Wed 15 Jul
Thu 16 Jul
Fri 17 Jul
Sat 18 Jul
Sun 19 Jul
Mon 20 Jul
Tue 21 Jul
Wed 22 Jul
Thu 23 Jul
Fri 24 Jul
Sat 25 Jul
Sun 26 Jul
Mon 27 Jul
Tue 28 Jul
Wed 29 Jul
Thu 30 Jul
Fri 31 Jul
Sat 1 Aug
Sun 2 Aug
Mon 3 Aug
Tue 4 Aug
Wed 5 Aug
Thu 6 Aug
Fri 7 Aug

Calendar is capable of handling the year rollover as well, for example...

Calendar start = Calendar.getInstance();
start.set(2015, Calendar.DECEMBER, 25);
start.set(Calendar.DAY_OF_MONTH, Calendar.getInstance()
                .getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar end = Calendar.getInstance();
end.setTime(start.getTime());
end.set(Calendar.DAY_OF_MONTH,
                Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
end.add(Calendar.DATE, 7);

Calendar now = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy");

for (Date dt = start.getTime(); !start.after(end); start.add(
                Calendar.DATE, 1), dt = start.getTime()) {

    System.out.println(sdf.format(dt));
}

Here, I've set the start date to December and the output is now...

Tue 1 Dec 2015
Wed 2 Dec 2015
Thu 3 Dec 2015
Fri 4 Dec 2015
Sat 5 Dec 2015
Sun 6 Dec 2015
Mon 7 Dec 2015
Tue 8 Dec 2015
Wed 9 Dec 2015
Thu 10 Dec 2015
Fri 11 Dec 2015
Sat 12 Dec 2015
Sun 13 Dec 2015
Mon 14 Dec 2015
Tue 15 Dec 2015
Wed 16 Dec 2015
Thu 17 Dec 2015
Fri 18 Dec 2015
Sat 19 Dec 2015
Sun 20 Dec 2015
Mon 21 Dec 2015
Tue 22 Dec 2015
Wed 23 Dec 2015
Thu 24 Dec 2015
Fri 25 Dec 2015
Sat 26 Dec 2015
Sun 27 Dec 2015
Mon 28 Dec 2015
Tue 29 Dec 2015
Wed 30 Dec 2015
Thu 31 Dec 2015
Fri 1 Jan 2016
Sat 2 Jan 2016
Sun 3 Jan 2016
Mon 4 Jan 2016
Tue 5 Jan 2016
Wed 6 Jan 2016
Thu 7 Jan 2016

Welcome to 2016 :)

I'd also encourage you to use Java 8's Time API or Joda-Time over Calendar

Objects, not strings

Use objects to represent your dates rather than depending on strings. Generate strings only for presentation to the user, but internally track your data as objects.

java.time.LocalDate

The Question and other Answer use troublesome old legacy date-time classes. Avoid them. Now supplanted by the java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );

Get the first of this month by calling withDayOfMonth .

LocalDate firstOfCurrentMonth = today.withDayOfMonth( 1 ); // Get first of this month.

Get the date of a week later than today.

LocalDate weekLaterThanToday = today.plusWeeks( 1 );

Collect all the possible dates between firstOfCurrentMonth and weekLaterThanToday . Note that usually it makes sense to track spans of time using the Half-Open approach where the beginning is inclusive and the ending is exclusive . So we are not collecting a LocalDate object for your end, your 7th day after today.

We can set the initial capacity of our collection to the number of days in our span of time. Use the ChronoUnit enum to calculate number of days.

int countDays = ChronoUnit.DAYS.between( firstOfCurrentMonth , weekLaterThanToday ) ;
List<LocalDate> dates = new ArrayList<>( countDays );
LocalDate ld = firstOfCurrentMonth;
while ( ld.isBefore( weekLaterThanToday ) ) {
    dates.add( ld );
    // Prepare for next loop.
    ld = ld.plusDays( 1 ); // Handles intelligently end-of-month, Leap Year, end-of-year, and so on.
}

You can loop that collection to generate text for presentation. The DateTimeFormatter class can automatically localize the generated string. Specify a FormatStyle for length of abbreviation. Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.

Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( l ) ; 

Loop your LocalDate objects, asking each to generate a String representation of its value.

for( LocalDate ld : dates ) {
    String output = ld.format( f );
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to java.time.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use… ).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM