0

Sorry for my bad English,I have list of dates coming from json

{
    "data": [
        {
            "lead_id": "1763",
            "name": "Gaurav Kumar",
            "date": "16-02-2020",
            "time": "10:00 To 11:00 AM",
        },
        {
            "lead_id": "1759",
            "name": "Test",
            "date": "04-02-2020",
            "time": "10:00 To 11:00 AM",
        },
        {
            "lead_id": "1751",
            "name": "kavita sharma",
            "date": "08-02-2020",
            "time": "10:00 To 11:00 AM", 
        },
        {
            "lead_id": "1751",
            "name": "kavita sharma",
            "date": "09-02-2020",
            "time": "10:00 To 11:00 AM",
        }
    ]
}

Below code helps me to find the current date

Calendar calendar = Calendar.getInstance();
        Date today = calendar.getTime();

        @SuppressLint("SimpleDateFormat")
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

        todayAsString = dateFormat.format(today);

        System.out.println(todayAsString);

But i want to know how can i check if the list of date is of the same month.

//Here is the code the i used to check the current date but i want to check if the all dates is of the same months.PLease let me know how could i do this

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://delhidailyservice.com/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APIService request = retrofit.create(APIService.class);
        Call<LeadData> call = request.leadData(prefConfig.readLoginId());
        call.enqueue(new Callback<LeadData>() {
            @Override
            public void onResponse(Call<LeadData> call, Response<LeadData> response) {

               /* new Handler().postDelayed(new Runnable() {
                    public void run() {
                        // if (isAdded()) {
                        pDialog.dismiss();
                        // }
                    }
                }, 5000);*/

                pDialog.dismiss();

                LeadData allEvent = response.body();
                allEventData = (List<Leads>) allEvent.getData();
//                Log.d("Error", ""+allEventData.size());

                allEventDatanew.clear();
                for (int i = 0; i < allEventData.size(); i++) {

                    if (todayAsString.equalsIgnoreCase(allEventData.get(i).getDate())) {
                        Leads allevent = new Leads();


                        String service = allEventData.get(i).getService();
                        String date = allEventData.get(i).getDate();
                        String name = allEventData.get(i).getName();
                        String time = allEventData.get(i).getTime();
                        String city = allEventData.get(i).getCity();
                        String status = allEventData.get(i).getStatus();
                        String credit = allEventData.get(i).getCredit();
                        String address = allEventData.get(i).getAddress();
                        String id = allEventData.get(i).getLeadId();

                        try {
                            //String details = allEventData.get(i).getDetail();

                            //abcd = Html.fromHtml(details).toString();

                            // tv_detail.setText(abcd);


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


                        allevent.setService(service);
                        allevent.setDate(date);
                        allevent.setName(name);
                        allevent.setTime(time);
                        allevent.setCity(address + " , " + city);
                        allevent.setStatus(status);
                        allevent.setCredit(credit);
                        allevent.setLeadId(id);


                        allEventDatanew.add(allevent);


                    }

                }
                // Log.d("Error1", ""+allEventDatanew.size());

                individualDataAdapter = new LeadAdapter(allEventDatanew, getContext());

                recyclerViewIndividualEvent.setAdapter(individualDataAdapter);
                individualDataAdapter.notifyDataSetChanged();
  • 1
    Does this answer your question? [Java: check if a given date is within current month](https://stackoverflow.com/questions/26824020/java-check-if-a-given-date-is-within-current-month) – Seb Feb 04 '20 at 13:10
  • no please check i just edited my question – Ashish Kumar Feb 04 '20 at 13:12
  • 3
    Please do not simply paste a huge fragment from your code here. This is nearly impossible to understand without knowing the exact context. Have a look here to see how to properly add code examples here: https://stackoverflow.com/help/minimal-reproducible-example – Seb Feb 04 '20 at 13:23
  • 1
    As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Feb 04 '20 at 14:38

3 Answers3

1

java.time and ThreeTenABP

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");

    List<Leads> allEventData = Arrays.asList(new Leads("16-02-2020"),
            new Leads("04-02-2020"), new Leads("08-02-2020"),
            new Leads("09-02-2020"));

    if (allEventData.isEmpty()) {
        System.out.println("No data");
    } else {
        YearMonth month = YearMonth.parse(allEventData.get(0).getDate(), dateFormatter);
        boolean otherMonthFound = false;
        for (Leads lead : allEventData) {
            if (! YearMonth.parse(lead.getDate(), dateFormatter).equals(month)) {
                otherMonthFound = true;
                break;
            }
        }
        if (otherMonthFound) {
            System.out.println("They are not all in the same month");
        } else {
            System.out.println("They are all in the same month " + month);
        }
    }

Output from this snippet is:

They are all in the same month 2020-02

I left out the other fields from the Leads class I used since they make no difference for the solution.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

LocalDate

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

Tip: Educate the publisher of your data about the ISO 8601 standard for textual formats when exchanging date-time values. The date should be in format of YYYY-MM-DD. The time-of-day range should be in 24-clock, with the pair of times separated by a slash character, ex. 11:00/15:00.

Your input is non-standard, so we must specify a formatting pattern to match. We use DateTimeFormatter.

String input = "16-02-2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu` ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

YearMonth

The YearMonth class represents an entire month.

Getting the current month requires a time zone. For any given moment, the date varies around the globe by time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
YearMonth ymCurrent = YearMonth.now( z ) ;

Get month of your input.

YearMonth ym = YearMonth.from( ld ) ;

Compare.

if( ym.equals( ymCurrent ) ) { … }

To see a further example of how to use this code to solve your problem, see the correct Answer by Ole V.V.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You can use this function

private void checkDate() {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
            Date date = new Date();
            String currentMonth = dateFormat.format(date);
            Log.d("Current Month", dateFormat.format(date));


            JSONObject jsonObject = new JSONObject(jsonData);

            JSONArray jsonArray = jsonObject.getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject innerJsonObject = jsonArray.getJSONObject(i);
                String jsonDate = innerJsonObject.getString("date");
                SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
                Date modifiedDate = format.parse(jsonDate);
                String monthString = (String) DateFormat.format("MM", modifiedDate);


                if (TextUtils.equals(monthString, currentMonth)) {
                    Log.d(TAG, "Match " + jsonDate);
                    //TODO:
                } else {
                    Log.d(TAG, "Mismatch " + jsonDate);
                    //TODO:
                }

            }

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


    }

Explanation

  1. Initially, I have created a local variable currentMonth which gets the current month digit from the device.
  2. I have parsed your JSON Array data and fetched the date value from the inner json object of the array.
  3. I used SimpleDateFormat class to fetch the month part from the date value (modifiedDate) and stored it inside monthString.
  4. This will return me the month value as String.
  5. I have used String Comparison to verify whether the current month and the parsed month is same or not.

If you really want to know whether all the dates in the JSON Array of the current month or not, you can use this function

private boolean checkAllDates(String jsonData) throws Exception {

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
        Date date = new Date();
        String currentMonth = dateFormat.format(date);

        JSONObject jsonObject = new JSONObject(jsonData);
        JSONArray jsonArray = jsonObject.getJSONArray("data");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject innerJsonObject = jsonArray.getJSONObject(i);
            String jsonDate = innerJsonObject.getString("date");
            SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
            Date modifiedDate = format.parse(jsonDate);
            String monthString = (String) DateFormat.format("MM", modifiedDate);
            if (!TextUtils.equals(monthString, currentMonth)) return false;
        }

        return true;

    }
Atish Agrawal
  • 2,857
  • 1
  • 23
  • 38
  • The `SimpleDateFormat` and `Date` classes are now legacy. These terrible classes were years ago supplanted by the modern *java.time* classes defined in JSR 310. – Basil Bourque Feb 04 '20 at 17:48