0

I'm really new in this area. But I want to find out e.g. the first sunday in July 2013 and then Android should calculate the days between now and then. Thank you so much for helping!

  • Try this link it has a no. of solutions to your problem: http://stackoverflow.com/questions/3838527/android-java-date-difference-in-days – Nitesh Verma Jul 02 '13 at 16:23
  • Java has great date and time functionality built in. Maybe a bit more research next time on Calender examples for java. – yams Jul 02 '13 at 16:29

2 Answers2

3
 Calendar thatDay = Calendar.getInstance();
  thatDay.set(Calendar.DAY_OF_MONTH,25);
  thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
  thatDay.set(Calendar.YEAR, 1985);

  Calendar today = Calendar.getInstance();

  long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis

Here's an approximation...

long days = diff / (24 * 60 * 60 * 1000);

To Parse the date from a string, you could use

  String strThatDay = "1985/08/25";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
  Date d = null;
  try {
   d = formatter.parse(strThatDay);//catch exception
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 


  Calendar thatDay = Calendar.getInstance();
  thatDay.setTime(d); //rest is the same....
marshallino16
  • 2,645
  • 15
  • 29
  • thanks, the differences are calculating, but how can I find out e.g. the first monday, sunday or sth else in a month??? It should say that the first sunday in july is 7.7.2013 e.g. –  Jul 02 '13 at 16:22
2

If you are going to some advanced calculations on dates in Java, I recommend Joda library (http://joda-time.sourceforge.net).

Using this library to solve your problem, it could be done like this:

LocalDate firstSundayOfJuly = new LocalDate(2013, 7, 1);
firstSundayOfJuly = firstSundayOfJuly.dayOfWeek().withMaximumValue();
Interval i = new Interval(LocalDate.now().toDateTimeAtStartOfDay(), 
            firstSundayOfJuly.toDateTimeAtStartOfDay());
System.out.println("days = " + i.toDuration().getStandardDays());
plw
  • 59
  • 1