1

I am developing an android application and i am getting start date and end date from the server.

Eg: 20-06-2016 and 20-06-2017

I want to find the list of dates between these two dates with interval of 10 days. excluding saturday and sunday.

for example: 20-06-2016 is monday so the next date should be 04-07-2016(excluded saturday and sunday). and so on.

After that on each date(from the list of dates) i want to add event in the calendar on that particular date so that i can notify the user with some message.

I wrote the code that adds event in the calendar and notify the user on particular time. so now i just want the list of dates.

Please help me out.

Thank you.

chetan
  • 681
  • 4
  • 21
  • 1
    Questions seeking debugging help (**"why isn't this code working?"**) must include *the desired behavior*, *a specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Gustavo Morales Jun 29 '16 at 10:08
  • @chetan Please check my code, it really works.:) – Dhruvi Jun 29 '16 at 11:02

5 Answers5

4

I somehow managed to accomplished this task.

Here is the code

public List<String> findDates(String startDate,String endDate) throws ParseException {
        List<Date> dates = new ArrayList<Date>(); //this list will store all the dates from startDate to endDate
        List<String> intervalDates = new ArrayList<>(); //this list will store dates excluding saturday and sunday.

        DateFormat formatter;
        formatter = new SimpleDateFormat("MM-dd-yyyy");

        Date sDate = (Date) formatter.parse(startDate);
        Date eDate = (Date) formatter.parse(endDate);
        long interval = 24 * 1000 * 60 * 60; // 1 day in millis
        long endTime = eDate.getTime(); // create your endtime here, possibly using Calendar or Date
        long curTime = sDate.getTime();
        while (curTime <= endTime) {
            dates.add(new Date(curTime)); 
            curTime += interval;  //adding the interval of 1day
        }

        for (int i = 0; i < dates.size(); i++) {
            Date lDate = (Date) dates.get(i); // getting each date from the list of all dates to find the day name
            String ds = formatter.format(lDate);

            Date day = formatter.parse(ds);
            DateFormat dayFormat = new SimpleDateFormat("EEEE");
            String dy = dayFormat.format(day); // to get the day name

            if (dy.equalsIgnoreCase("Saturday") || dy.equalsIgnoreCase("Sunday")) {
                continue;
            }
            intervalDates.add(ds); //adding date excluding saturday and sunday.

            //Log.d(TAG, "findDates: Date is:" + ds + " " + dy);
        }
        return intervalDates;
    }
chetan
  • 681
  • 4
  • 21
1

The output of the code below is:

20-06-2016
04-07-2016

I hope it helps

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloWorld{

    public static void main(String []args) throws ParseException{
        String str = "20-06-2016";
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        Date date = formatter.parse(str);
        String dater = formatter.format(date);
        System.out.println(dater);
        Date dateNew = new Date(date.getYear(), date.getMonth(), date.getDate() +14);
        System.out.println(formatter.format(dateNew));
     }
}

sources:

How to add one day to a date?

How to parse a date?

Community
  • 1
  • 1
emrah
  • 140
  • 1
  • 7
0

To work with date and time interval, i suggest you to use JodaTime library. It contains all functionality you need.

http://www.joda.org/joda-time/

http://joda-time.sourceforge.net/userguide.html

It's a jar so you can easily include in your project.

Hope it helps.

xcesco
  • 4,690
  • 4
  • 34
  • 65
0

emrah answer is ok for simple cases, but if you must exclude sundays and saturdays, I would suggest to use an instance of Calendar class. For example:

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.US);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(format.parse("26-06-2016"));
    int dow = calendar.get(Calendar.DAY_OF_WEEK);
    if (dow == Calendar.SATURDAY)
        calendar.add(Calendar.DATE, 2);
    else if (dow == Calendar.SUNDAY)
        calendar.add(Calendar.DATE, 1);

    int intervalCount = 10;
    // List of dates
    List<Date> dates = new ArrayList<>(intervalCount);
    for(int i = 0; i < intervalCount; i++) {
        // Two weeks, I guess
        calendar.add(Calendar.DATE, 14);
        dates.add(calendar.getTime());
    }

    for (Date date : dates) {
        Log.e(TAG, format.format(date));
    }

Calendar documentation

Community
  • 1
  • 1
kaplis
  • 63
  • 7
0

Try below code, it must help:

public class MainActivity extends AppCompatActivity {

public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
int no_of_days = 0;
List<Date> dates = null;
RecyclerView recycler_view;
Calendar calendar = null;

RecyAdapter recyAdapter = null;
LinearLayoutManager linearLayoutManager = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    recycler_view = (RecyclerView) findViewById(R.id.recycler_view);

    dates = new ArrayList<>();

    linearLayoutManager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false);
    recycler_view.setLayoutManager(linearLayoutManager);
    no_of_days = getNoOfDays("20-06-2016", "20-08-2016");

    calendar = Calendar.getInstance();
    try {
        calendar.setTime(new SimpleDateFormat("dd-MM-yyyy").parse("20-06-2016"));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < no_of_days; i++) {
        calendar.add(Calendar.DATE, 10);
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
                || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
        } else {
            dates.add(calendar.getTime());
        }
    }

    recyAdapter = new RecyAdapter(MainActivity.this, dates);
    recycler_view.setAdapter(recyAdapter);

}

public int getNoOfDays(String Created_date_String, String Expire_date_String) {

    Date Created_convertedDate = null, Expire_CovertedDate = null, todayWithZeroTime = null;
    try {
        Created_convertedDate = DATE_FORMAT.parse(Created_date_String);
        Expire_CovertedDate = DATE_FORMAT.parse(Expire_date_String);

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

    Calendar createdDay = Calendar.getInstance();
    createdDay.setTime(Created_convertedDate);

    Calendar expireDay = Calendar.getInstance();
    expireDay.setTime(Expire_CovertedDate);

    long diff = createdDay.getTimeInMillis() - expireDay.getTimeInMillis();

    long days = (diff / (24 * 60 * 60 * 1000));

    return (Math.abs((int) days))/10;
}
}

Its Adapter class is as below:

public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.ViewHolder> {


Context context;
List<Date> dates = null;

public RecyAdapter(Context context, List<Date> dates) {

    this.context = context;
    this.dates = dates;
}


@Override
public RecyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.row_item, parent, false);
    ViewHolder viewHolder = new ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(final RecyAdapter.ViewHolder holder, int position) {

    holder.txt.setText(MainActivity.DATE_FORMAT.format(dates.get(position)));

}

@Override
public int getItemCount() {
    return dates.size();
}

class ViewHolder extends RecyclerView.ViewHolder {
    TextView txt;

    public ViewHolder(View itemView) {
        super(itemView);
        txt = (TextView) itemView.findViewById(R.id.txt);
    }
}

}

And its layout are:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="fitness.vario.stacklistofdates.MainActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal" />
</RelativeLayout>

row_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:id="@+id/txt"/>

</LinearLayout>
Dhruvi
  • 1,971
  • 2
  • 10
  • 18