简体   繁体   中英

Get week days getter

I want to get week days between two dates, return type should be string array which consist of week days such (''Sunday", "Monday"....etc) could you please help me to clarify this issue. i have no idea with this

As per my problem i want to get week days between start date end date as per below

SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy");
    String startDate="01/07/2015";
    String endDate="31/07/2015";
    try {
        Date sDate=myFormat.parse(startDate);
        Date eDate=myFormat.parse(endDate);


    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

First, try and find the difference in days between the start and end dates:

long startTime = sDate.getTime();
long endTime = eDate.getTime();
long differenceMillis = endTime - startTime;
// divide by the number of millis per day
int differenceInDays = Math.ceil((double) differenceMillis / MILLIS_PER_DAY);

Then, you can find on which day of the week does your interval start:

Calendar startCal = Calendar.getInstance();
startCal.setTime(sDate);
// if you need to skip the actual start day from the interval, add a day to the calendar
int dayOfWeek = startCal.get(DAY_OF_WEEK);

After you have your start day of the week and the difference between the dates, you can loop and add the appropriate values to your resulting list:

List<String> days = new LinkedList<>();
for (int i = 0; i < differenceInDays; i++) {
    dayOfWeek++;
    if (7 < dayOfWeek) {
        // if we have reached the last day of the week, we reset to the first day of the week
        dayOfWeek = 1;
    }

    switch (dayOfWeek) {
        case Calendar.SATURDAY:
            days.add("Saturday");
            break;
        // add other cases here
    }
}

This should be the basic steps you need to follow. The code is just an example, you can optimise and adapt it to use the best practices.

Edit: Fixed a bug in the for loop - dayOfWeek should be incremented by one on each iteration, not by i . Now it should work OK.

private void generateDays() {

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    List<String> weekDays = new ArrayList<String>();

    try {
        Date parse = sdf.parse("01/07/2015");
        Date parse2 = sdf.parse("31/07/2015");

        long start = parse.getTime();
        long stop = parse2.getTime();

        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(start);

        for (int i = 0; c.getTimeInMillis() <= stop; i++) {
            String date = getDate(c.getTimeInMillis(), "EEEE");
            weekDays.add(date);
            Log.d("xxx", (i + 1) + " " + date);
            c.add(Calendar.DAY_OF_MONTH, 1);
        }

    } catch (ParseException e) {
        e.printStackTrace();
    }
}

public static String getDate(long milliSeconds, String dateFormat) {
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return formatter.format(calendar.getTime());
}

java.time

Use the modern java.time classes that supplant the troublesome old date-time classes.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate start = LocalDate.parse( "01/07/2015" , f );
LocalDate stop = LocalDate.parse( "31/07/2015" , f );

List<LocalDate> dates = new ArrayList<>( ChronoUnit.DAYS.between( start , stop ) + 1 );
LocalDate ld = start ;
while ( ! ld.isAfter( stop ) ) {
    dates.add( ld );
    // Set up next loop.
    ld = ld.plusDays( 1 );
}

To get Strings of the name of the day of week, use the DayOfWeek enum and its ability to localize the name of the day of the week.

…
String output = ld.getDayOfWeek().getDisplayName( TextStyle.FULL_STANDALONE , Locale.US );  // Or Locale.CANADA_FRENCH etc.
…

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