I'm trying to set up a mechanism which calculates the difference between two date objects but I've got a problem. My first input which will be converted to a Date object is:
Ma 14:00
Which means 'Monday 14:00'. I'm converting this string into a date object with the following code.
try {
date = new SimpleDateFormat("EE HH:mm", Locale.getDefault()).parse(msg);
Log.i("intent", "Date: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
If I print the Date object it is 'Mon Jan 05 14:00:00 CET 1970'. I'm only interested in the day name and the time, so I didn't bother changing the other parts of the date object.
My problem is the following: I need to know the difference between the day now (example: thursday) and the day from above (example: monday).
I tried to do the following:
Date dateNow = new Date();
dateNow.setHours(date.getHours());
dateNow.setMinutes(date.getMinutes());
dateNow.setSeconds(date.getSeconds());
dateNow.setYear(70);
dateNow.setMonth(0);
Log.i("DAYS TAG", ""+dateNow);
long diff = date.getTime() - dateNow.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
Log.i("DAYS TAG", ""+days);
This way didn't work out because I was working with the days, but the days were negative or sometimes not accurate.
Basically what I want is this:
- Get date with upcoming day (just as above monday)
- Get current date (thursday)
- Calculate the difference between those days (4 days)
With these steps I found this:
Calendar now = Calendar.getInstance();
int weekday = now.get(Calendar.DAY_OF_WEEK);
if(weekday != Calendar.MONDAY){
int days = (Calendar.SATURDAY - weekday + 2) %7;
now.add(Calendar.DAY_OF_YEAR, days);
}
This gets the date of the upcoming monday. Just like I want in my first step. However when I added my old date, it didn't work again. It gave a wrong date back. The updated code was:
//get difference in days between now and date object.
Calendar old = Calendar.getInstance();
old.setTime(date);
Log.i("...",""+old.get(Calendar.DAY_OF_WEEK));
Calendar now = Calendar.getInstance();
int weekday = now.get(Calendar.DAY_OF_WEEK);
if(weekday != Calendar.MONDAY){
int days = (Calendar.SATURDAY - weekday + 2) %7;
now.add(Calendar.DAY_OF_YEAR, days);
}
Date date2 = now.getTime();
Log.i("tag", ""+date2);
But as I said, it gives back the wrong date.
I would really appreciate it if anyone would help. Because I've been working a few hours on this already.