-1

In my app i count no of days difference between old date and new date with the following code. it work good on android 2.2 and 2.3.6 devices but on android 4.0 device it is get crashed with java.lang.IllegalArgumentException. i do not know sdk 4.0 does not support my code. please help me.

my code is :

Date date;
String old_Date = null;
.....
date = new Date();
old_Date = date.toString(); // i am storing it in sharedPreference so that i convert to string 
.......
date = new Date();
long diff = calculate_dateDifference(date,new Date(old_Date));  // line no 65.
...

and my method:

    protected long calculate_dateDifference(Date newerDate, Date olderDate) {
        return (newerDate.getTime() - olderDate.getTime()) / (1000 * 60 * 60 * 24);
    }

my sample log cat:

Caused by: java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:506)
at java.util.Date.<init>(Date.java:149)
at com.xxx.zzz.MainActivity.onCreate(MainActivity.java:65)
M.A.Murali
  • 9,988
  • 36
  • 105
  • 182
  • 1
    To put it simply, it's not in your code, its how you initialize the Date because the parse() is failing. Try using a SimpleCalendar instead. – Shark Nov 02 '12 at 14:48
  • hi.. i also had same error. Did you got solution? Please help me – Shalini Feb 25 '13 at 11:19
  • @Shalini, I have used currentTimeMillis() to calculate between two days. protected long calculate_dateDifference(long newerDate, long olderDate) { return (newerDate - olderDate) / (1000 * 60 * 60 * 24); } – M.A.Murali Feb 25 '13 at 12:30

5 Answers5

0

Look at this part

calculate_difference(date, new Date(old_date));

//and earlier
old_Date = date.toString();

obviously you can no longer instantiate a Date object from a String. You'll have to figure something out, but I suggest using SimpleCalendar and DateFormat - use the DateFormat to store your String in SharedPreferences.

Shark
  • 6,513
  • 3
  • 28
  • 50
0

public Date (String string) is deprecated method since java1.1, not guranteed to behave as you expected.

If you have string and would like to convert it to date use

DateFormat df = DateFormat.getDateInstance();
myDate = df.parse(myString);

Here is DateFromat javadoc

kosa
  • 65,990
  • 13
  • 130
  • 167
0

I would suggest storing the miliseconds instead of a date strings. As a bonus, you can instantiate a date with a long parameter representing the milliseconds.

Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148
0

Maybe use the date with timestamp:

System.currentTimeMillis();
Algodrill
  • 126
  • 7
0

Depending on your date format, you can use the following code,

Date oldDate   = new SimpleDateFormat("dd-MM-yyyy").parse("29-10-2012");
Date newerDate = new Date();

int dayInMillisecs = 1000 * 60 * 60 * 24;

int dayDifference = (int) ((newerDate.getTime() - oldDate.getTime()) / dayInMillisecs);
Can Elmas
  • 487
  • 1
  • 7
  • 14