简体   繁体   中英

Check the difference between todays date and a previous date in android

I have to find the day difference between todays date and another previous date. How can i find??

I write the code :

Calendar calfromDate = Calendar.getInstance();
calfromDate.set(m_nVYear, m_nVMonth, m_nVDay);
long m_lDate = calfromDate.getTimeInMillis();
Calendar calToday = Calendar.getInstance();
long today = calToday.getTimeInMillis();
Log.d("debug", "today:" +today);
Log.d("debug", "from date:" +m_lDate);
int day_difference = (int)((m_lDate - today)/(24*60*60*1000));

From http://tripoverit.blogspot.com/2007/07/java-calculate-difference-between-two.html :

public static long daysBetween(Calendar startDate, Calendar endDate) {  
   Calendar date = (Calendar) startDate.clone();  
   long daysBetween = 0;  
   while (date.before(endDate)) {  
     date.add(Calendar.DAY_OF_MONTH, 1);  
     daysBetween++;  
   }  
   return daysBetween;  
 }  

Try with the following code

// Creates two calendars instances
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();

    // Set the date for both of the calendar instance
    cal1.set(2006, 12, 30);
    cal2.set(2007, 5, 3);

    // Get the represented date in milliseconds
    long milis1 = cal1.getTimeInMillis();
    long milis2 = cal2.getTimeInMillis();

    // Calculate difference in milliseconds
    long diff = milis2 - milis1;

    // Calculate difference in seconds
    long diffSeconds = diff / 1000;

    // Calculate difference in minutes
    long diffMinutes = diff / (60 * 1000);

    // Calculate difference in hours
    long diffHours = diff / (60 * 60 * 1000);

    // Calculate difference in days
    long diffDays = diff / (24 * 60 * 60 * 1000);

    System.out.println("In milliseconds: " + diff + " milliseconds.");
    System.out.println("In seconds: " + diffSeconds + " seconds.");
    System.out.println("In minutes: " + diffMinutes + " minutes.");
    System.out.println("In hours: " + diffHours + " hours.");
    System.out.println("In days: " + diffDays + " days.");

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