Fill Array With incremented Date value in Android

▼魔方 西西 提交于 2020-02-05 06:57:49

问题


//Well i have gone through so many tutorial but coudlnt find my thing so i am here to put up my query i have two DatePicker FromDate and ToDate What i want is when User selext the date it should come in a String Array of Dates suppose my date is Start_Date="1/09/2012" i want to fill Array like

String[] Date Arrau= {"1/09/2012","2/09/2012","3/09/2012","4/09/2012"} 

What i have done is

    DateDifference=Integer.parseInt(EndDate)-Integer.parseInt(StartDate);

SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");

    Date myDate= null;
    try {
        myDate= sdf.parse(StartDate);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Date newFirstDate= new Date(myDate.getDate()); // 7 * 24 * 60 * 60 * 1000

    for(int i=0;i<=DateDifference;i++){
        Calendar c= Calendar.getInstance();
        c.setTime(newFirstDate);
        c.add(Calendar.DATE, 1);
        Date newDate= c.getTime();  
        DateArray[i]=newDate.toString();

    }

i am getting a null pointer Exception Error

it is giving me error Please help !!


回答1:


Create startDate and endDate like this

   Calendar startDate, endDate;
   startDate = Calendar.getInstance();
   endDate = Calendar.getInstance();

        startDate.clear();
        endDate.clear();

        startDate.set(2012, 8, 1);
        endDate.set(2012, 8, 30); 
        ArrayList<String> list = getList(startDate, endDate);

This method is generating an arrayList.

public ArrayList<String> getList(Calendar startDate, Calendar endDate) {
        ArrayList<String> list = new ArrayList<String>();
        while (startDate.compareTo(endDate) <= 0) {
                    list.add(getDate(startDate));
            startDate.add(Calendar.DAY_OF_MONTH, 1);
        }
        return list;

    }

Use this to format the date string

public String getDate(Calendar cld) {

        String curDate = cld.get(Calendar.YEAR) + "/" + (cld.get(Calendar.MONTH) + 1) + "/"
                + cld.get(Calendar.DAY_OF_MONTH);
        try {
            Date date = new SimpleDateFormat("yyyy/MM/dd").parse(curDate);

            curDate = new SimpleDateFormat("yyyy/MM/dd").format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return curDate;
    }


来源:https://stackoverflow.com/questions/12597614/fill-array-with-incremented-date-value-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!