简体   繁体   中英

Difference between two dates?

Friends, I am looking to calculate the difference in days.

Hey suppose if I enter 31st Aug 23:59:00 and next date 1 Sept 00:02:00 , I need to show the record as 1 day.

Please help me for this one.

Right now I am calculating the same using .getTimeInMillis() but it is not giving me expected results for the date condition mentioned above.

I you look for day and time difference then, use my code

public class AndroidWebImage extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  Date sdate=Calendar.getInstance().getTime();
  SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy HH:mm:ss");

  String setDate = "13/09/12 10:20:43";
  Date AlarmDate=new Date(setDate);
  String currentDate = format.format(sdate);

  Date d1 = null;
  Date d2 = null;
  try {
      d1 = format.parse(setDate);
      d2 = format.parse(currentDate);
  } catch (ParseException e) {
      e.printStackTrace();
  }    
 //Comparison
  long diff = d1.getTime() - d2.getTime();
  long diffSeconds = diff / 1000 % 60;  

  long days = (int) (diff / (1000 * 60 * 60 * 24));
  long diffHours = (int) ((diff- (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
  long diffMinutes = (int) (diff- (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 *      diffHours))/ (1000 * 60);

  int curhour=sdate.getHours();
  int curmin=sdate.getMinutes();
  int alarmhour=AlarmDate.getHours();
  int alarmmin=AlarmDate.getMinutes();
  if(curhour==alarmhour && curmin==alarmmin)
  {
      Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
  }
  else if(curhour>=alarmhour && curmin>=alarmmin || curhour<=alarmhour && curmin<=alarmmin)
  {
      Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
  }




 }
}

You need to get rid of the timestamps and then subtract dates to get the difference in dates or you can use Joda-time as below:

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date past = new Date(112, 8, 1); 
Date today = new Date(112, 7, 30); 
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); 

You can't do this with millis, because you need to know where the day boundary falls (ie midnight). A millisecond either side of midnight means two different days.

You need to use a Calendar to determine how many days lie within the interval between your two dates. The JodaTime library has a lot of additional support for this kind of calculation.

See also Calculating the difference between two Java date instances

Your're just trying to find the number of days, right?

Try looking at this , it might have what you are looking for.

i made this code before, its may helps you

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author MErsan
 */
public class DateFormatter {

    public static String formatDate(long time) {
        StringBuilder result = new StringBuilder();

        // 1- Check the year
        // 2- Check the Month
        // 3- Check the Day
        // 4- Check the Hours

        Date myDate = new Date(time);
        Date todayDate = new Date(System.currentTimeMillis());

        if (todayDate.getYear() - myDate.getYear() != 0) {
            // Not same year, and should append the whole time
            return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
        }
        // Same Year
        // now Check the month
        if (todayDate.getMonth() - myDate.getMonth() != 0) {
            return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
            // 16,
            // 11:55
            // PM
        }

        // Now Same Month
        // Check the day
        int daysDiff = todayDate.getDate() - myDate.getDate();
        if (daysDiff == 1) {// Yesterday
            result.append("Yesterday").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (daysDiff != 0) {
            return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
            // 16,
            // 11:55
            // PM
        }

        // Same Day :')
        // Check the hour
        int hoursDiff = todayDate.getHours() - myDate.getHours();
        if (hoursDiff < 0) {// Invalid Time
            // :@
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (hoursDiff != 0) {// Hours Diff less than 3 hours, but not
            // current hour
            int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();

            result.append("Before").append(' ');
            result.append(hoursDiff).append(' ');
            result.append("Hours").append(' ');
            result.append("and").append(' ');
            result.append(Math.abs(mintuesDiff)).append(' ');
            result.append("Minutes");
            System.err.println("Case 6");
            return result.toString();
        } else if (hoursDiff == 0) {// Same Hours
            int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
            if (mintuesDiff < 1) {// Seconds Only {Same Minute}
                int secondsDiff = todayDate.getSeconds() - myDate.getSeconds();
                result.append("Before").append(' ');
                result.append(Math.abs(secondsDiff)).append(' ');
                result.append("Seconds");
                return result.toString();
            } else {
                result.append("Before").append(' ');
                result.append(Math.abs(mintuesDiff)).append(' ');
                result.append("Minutes");
                return result.toString();
            }
        }

        // Default
        return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
    }
}
import java.util.Calendar;

public class DateDifference
{  
    public static void main(String[] args)
    {
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();

        calendar1.set(2012, 01, 10);
        calendar2.set(2012, 07, 01);

        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();

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

        System.out.println("Time in days: " + diffDays + " days.");
    }
} 

Re-post :

There's a simple solution, that at least for me, is the only feasible solution.

The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates , rather than the actual number of days . So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.

To count the actual number of days between startDate and endDate , simply do:

// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;

// Find the difference, duh
long daysBetween = endDay - startDay;

This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM