-3

Hello Guys This problem is driving me crazy right now. I have a string in my database called dueDate with value Jan 18, 2018. I retrieved it and save it in a string in my recyclerAdapter with String dueDate = transactionTasks.get(position).get_transactiontaskpaydet().toString();

Now i wanna compare it with the current date and if the due date is after my current date it should display the dueDate with red color.

bellow are my coded.

String dueDate = transactionTasks.get(position).get_transactiontaskpaydet().toString();
    Date cdate = new Date();
    Date ddate = new Date(dueDate);

    if(cdate.after(ddate)){
        holder.date.setTextColor(Color.RED);
    }

This codes work perfectly but the problem is Date(dueDate); is deprecated. And when i use another method that uses a try and catch, i don't get any result.

Below are the codes

SimpleDateFormat format = new SimpleDateFormat("E, MMM dd yyyy");
    Date curDate = new Date();
        try {
            Date datedue = format.parse(dueDate);
            if(curDate.after(datedue)) {
                holder.date.setTextColor(Color.RED);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

And if I try creating the Date outside the try block by using Date duedate = null; I get an error because its not getting the values inside the try block. this is driving me crazy because I shouldn't use deprecated code even if it works perfectly.

All the answers I found didn't work for me. I just need to be able to convert a string to a date so I can compare it with the current date. Thanks Guys

  • Use Calendar cal = Calendar.getInstance(); instead – RaniDevpr Dec 15 '17 at 21:10
  • This is just another "how do I parse a date with an odd syntax" question. I have linked to a generic Q&A which (among other things) explains how to create a date format that matches your date syntax. (If that Q&A doesn't work for you, then you have not read it properly!) – Stephen C Dec 16 '17 at 03:39

1 Answers1

2

I think the issue is with your SimpleDateFormat. If your String really is "Jan 18, 2018" then you need your SimpleDateFormat to match that like this:

SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");

I made a quick method to test this and it worked fine:

public static void main(String args[]) {
    String dueDate = "Jan 18, 2018";
    SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
    Date curDate = new Date();
    try {
        Date datedue = format.parse(dueDate);
        if(curDate.after(datedue)) {
            holder.date.setTextColor(Color.RED);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I hope this helps!

Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28
  • Yes but what I was missing is `Locale.ENGLISH` and that was why I kept getting the error. so one it was added to `DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);` it worked – Ibrahim Usman May 04 '18 at 11:40