user6092898
user6092898

Reputation:

How to calculate the aging provided two dates?

I'm trying to implement this logic in my app where I have to calculate the aging process.

I will be getting the date along with time dynamically as a string.
For instance, it will be like following

String due_date = "2016-03-27 00:00:00"

To find the number of days between two dates, I have the following code

SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
Date dt1 = format1.parse("due_date");

But the problem is that I'm unable to do so because I'm getting a parse exception.

So,

  1. How can I be able to parse a string due_date?
  2. How can I be able to subtract current date from due_date to get the number of days between two dates?

Upvotes: 1

Views: 187

Answers (2)

Cootri
Cootri

Reputation: 3836

How can i be able to parse a string due_date?

You should use this format:

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dueDate = format1.parse(due_date);

How can I be able to subtract current date from due_date to get the number of days between two days?

you should write method like:

public static int getDaysBetweenDates(Date fromDate, Date dueDate) {
    return (int) ((dueDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24L));
}

and use it like this:

String from_date = "2016-03-26 00:00:00";
String due_date = "2016-03-27 00:00:00";

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = format1.parse(from_date);
Date dueDate = format1.parse(due_date);

System.out.println(getDaysBetweenDates(fromDate, dueDate));//prints "1"

Upvotes: 2

Aks4125
Aks4125

Reputation: 5720

Two ways to get total days between two dates

  • Using Date class

public static int getDaysDifference(Date fromDate,Date toDate) { if(fromDate==null||toDate==null) return 0; return (int)( (toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24)); }

  • using Calendar

public static int getDaysDifference(Calendar calendar1,Calendar calendar2) { if(calendar1==null||calendar2==null) return 0; return (int)( (calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / (1000 * 60 * 60 * 24)); } To format date follow @Cootri answer. :)

Upvotes: 0

Related Questions