0

I am having doubt that how can i iterate through the days in java (Android). Requirement is i am displaying whole week dates.

Note: "whichever date user selects from it should start".

ex: If date is 29-10-2017 then the output will be 29-10-2017, 30-10-2017, 31-10-2017, 1-11-2017, 2-11-2017, 3-11-2017, 4-11-2017. This is whole week.

I was able to get this result when dates are inside that month, but when dates are exceeding the month or year, i am not able to resolve them. Please help, how do i resolve this issue.

Below is the code-snippet which i am using for this:

    Calendar startCal = Calendar.getInstance();
    startCal.setTime(new Date(Long.MAX_VALUE));
    startCal.setTimeInMillis(minDate.getDateInMillis());
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(new Date(Long.MAX_VALUE));
    endCal.setTimeInMillis(maxDate.getDateInMillis());

    // Add all weekend days within range to disabled days
    for (int i = 0; i < 7; i++) {
        while (startCal.before(endCal) || startCal.equals(endCal) || (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)) {
            if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
                    || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
                    || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY
                    || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY
                    || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY
                    || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
                int key = Utils.formatDisabledDayForKey(startCal.get(Calendar.YEAR),
                        startCal.get(Calendar.MONTH), startCal.get(Calendar.DAY_OF_MONTH));
                disabledDays.put(key, new MonthAdapter.CalendarDay(startCal));
            }
            startCal.add(Calendar.DATE, 1);
        }
    }
    int daysInMonth = startCal.getActualMaximum(Calendar.DAY_OF_MONTH); // 31

And to poulet them inside some textview i am using this below code-snippet:

String date = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
    arr1 = new String[7];

    datepicker_dailog.setText(date);
//  String input = datepicker_dailog.getText().toString();

    Log.e(TAG, "Date value1 is:--- " + date);

    GregorianCalendar cal=new GregorianCalendar();
    if (cal.isLeapYear(year)) {
        dayOfMonth++;
    }

    String ar[] = date.split("[-]");
    int day = Integer.parseInt(ar[0]);
    int month = Integer.parseInt(ar[1]);
    int year1 = Integer.parseInt(ar[2]);

    Log.e(TAG, "new value is  "+ day + "  " + month + "  "+ year1);

    for(int j = 0; j < 7 ; j++) {
        date_exp(day, month, year1);
        date = day + "-"+month+"-"+year1;
        arr1[j] = date;
        Log.e(TAG, "loop is :---  "+ arr1[j]);


        Log.e(TAG, "value in loop is :---  "+ day + "  " + month + "  "+ year1);
        day++;
    }

    Log.e(TAG, "updated value is  "+ day + "  " + month + "  "+ year1);

I am refering this library to inplement calendar with date:

https://github.com/code-troopers/android-betterpickers

Here i am modifying and storing the date values in textviews, Please check once:

    @Override
    public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
    String date = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
    arr1 = new String[7];

    datepicker_dailog.setText(date);
//  String input = datepicker_dailog.getText().toString();

    Log.e(TAG, "Date value1 is:--- " + date);

    GregorianCalendar cal=new GregorianCalendar();
    if (cal.isLeapYear(year)) {
        dayOfMonth++;
    }

    String ar[] = date.split("[-]");
    int day = Integer.parseInt(ar[0]);
    int month = Integer.parseInt(ar[1]);
    int year1 = Integer.parseInt(ar[2]);

    Log.e(TAG, "new value is  "+ day + "  " + month + "  "+ year1);

    for(int j = 0; j < 7 ; j++) {
        date = day + "-"+month+"-"+year1;
        arr1[j] = date;
        Log.e(TAG, "loop is :---  "+ arr1[j]);


        Log.e(TAG, "value in loop is :---  "+ day + "  " + month + "  "+ year1);
        day++;
    }

    Log.e(TAG, "updated value is  "+ day + "  " + month + "  "+ year1);


    //------------------------------------------------------------------------------------------

    listView=(ListView)findViewById(R.id.addtime_container);
    dataModels= new ArrayList<>();
    try {
        for (int i = 0; i < 7; i++) {
            dataModels.add(new Model_Addtime(arr1[i]));

            adapter = new Adapter_addtime(dataModels, getApplicationContext());
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Model_Addtime dataModel = dataModels.get(position);

                    Snackbar.make(view, dataModel.getDate_text() + "\n", Snackbar.LENGTH_LONG).setAction("No action", null).show();
                }
            });
        }
    } catch (NumberFormatException num){
        num.printStackTrace(); num.getCause(); num.getMessage();
    }
}
amit pandya
  • 1,384
  • 13
  • 22
  • 2
    A good option for this is to use [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) and JSR-310, the modern Java date API: `LocalDate date = LocalDate.of(2017, Month.OCTOBER, 29); for (int i = 0; i < 7; i++) { System.out.println(date); date = date.plusDays(1); }`. – Ole V.V. Nov 27 '17 at 09:54
  • What erroneous results are you getting when you try to cross a month border? `startCal.add(Calendar.DATE, 1);` should handle this correctly. – Ole V.V. Nov 27 '17 at 09:56
  • but isn't its hard-coded for a particular month. I want to use it like whichever month and year user want to choose, he can choose. – amit pandya Nov 27 '17 at 09:57
  • I told in my question only, If date is 30-10 and the loop is running date is going out of bound to 31 32 33 34 like this... and month and year values also i am not able to handle properly. – amit pandya Nov 27 '17 at 10:00
  • @amitpandya - use my code as it is below. i have tested it. – Hirak Chhatbar Nov 27 '17 at 10:03
  • @HirakChhatbar, your code uses the long outmoded classes `SimpleDateFormat` and `Calendar`. Better to show how to use the modern API. – Ole V.V. Nov 27 '17 at 10:11
  • 1
    @OleV.V. wasn't aware about LocaleDate. That is why I upvoted your comment. Thnx – Hirak Chhatbar Nov 27 '17 at 10:14
  • As Ole V.V. commented, the old legacy date-time classes are an awful wretched mess. Use their replacement, the java.time classes. Much of the java.time functionality is back-ported to earlier Java and Android in the *ThreeTen-Backport* and *ThreeTenABP* projects. – Basil Bourque Nov 27 '17 at 16:53

4 Answers4

1

You should use this code

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
cal.add(Calendar.DATE, 2);
cal.add(Calendar.DATE, 3);

DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df.format(cal.getTime());

It will handle the month change and year change automatically.

In java 8 you can use streams like in this example

List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(toList());
muasif80
  • 5,586
  • 4
  • 32
  • 45
0

Get instance of calendar, set it to today's date. Calendar has a function of adding 1 day to specified date and it takes care of adding month, year etc. Below is the code. Haven't tested the code though.

// Define the format in which you want dates    
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

//Get calendar instance
Calendar calendar = Calendar.getInstance();

//Set today's date to calendar instance
calendar.setTime(new Date());

//Initialize a list to get dates
List<String> dates = new ArrayList<>();

//Get today's date in the format we defined above and add it to list
String date = format.format(calendar.getTime());
dates.add(date);

//run a for loop six times to get 1 day added each time
for (int i = 0; i <= 5; i++){
//this will take care of month and year when adding 1 day to current date
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    dates.add(format.format(calendar.getTime()));
}

//Then to show the dates to your text-
String listString = TextUtils.join(", ", dates);
yourtextview.setText(listString);
Hirak Chhatbar
  • 3,159
  • 1
  • 27
  • 36
  • can u please describe where i can use this snippet exactly, before showing in textview or in starting only.??? – amit pandya Nov 27 '17 at 09:47
  • Updated my code. Use this code as it is. I have tested it. – Hirak Chhatbar Nov 27 '17 at 09:54
  • listView=(ListView)findViewById(R.id.addtime_container); dataModels= new ArrayList<>(); for (int i = 0; i < 7; i++) { dataModels.add(new Model_Addtime(arr1[i])); adapter = new Adapter_addtime(dataModels, getApplicationContext()); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { Model_Addtime dataModel = dataModels.get(position); } }); } } Like this i am using in my code... – amit pandya Nov 27 '17 at 10:07
  • It looks like you are trying to how dates in a list. use the dates list in your adapter – Hirak Chhatbar Nov 27 '17 at 10:10
0

You can use the add() method of Calendar class. It can be used to add or subtract specified number of days to a Calendar instance. The following is a running piece of code

import java.text.SimpleDateFormat;  
import java.util.Date;
import java.util.Calendar;  
public class DateExample {  
public static void main(String[] args) {  
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    String date;
    for (int i = 0; i <= 7; i++){
        date = dateFormat.format(cal.getTime());                        
        System.out.println(date);           
        cal.add(Calendar.DAY_OF_MONTH, 1);

    }
    }  

}

0

You can use iterateDay method. Example usage also below.

public class DateClass {

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2017, Calendar.OCTOBER, 29);
        new DateClass().iterateDay(calendar.getTime(), 7);
    }

    public void iterateDay(Date date, int iterateCount){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        dislayDate(date);
        for (int i = 1; i < iterateCount; i++) {
            calendar.add(Calendar.DATE, 1);
            dislayDate(calendar.getTime());
        }

    }

    public void dislayDate(Date date){
        SimpleDateFormat dateFormat = new  SimpleDateFormat("dd-MM-yyyy");
        System.out.println(dateFormat.format(date));
    }
}
ramazankul
  • 452
  • 1
  • 4
  • 14