两个日期之间的差异?

时间:2012-09-25 11:14:25

标签: java android date

友 我希望计算天数的差异。

嘿,如果我输入 8月31日23:59:00 而下一个日期 1月9日00:02:00 ,我需要将记录显示为1天。

请帮帮我。

现在我正在使用.getTimeInMillis()计算相同内容,但它没有给出上述日期条件的预期结果。

7 个答案:

答案 0 :(得分:1)

我在寻找日期和时间差异,然后使用我的代码

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();
  }




 }
}

答案 1 :(得分:0)

您需要删除时间戳,然后减去日期以获取日期差异,或者您可以使用Joda-time,如下所示:

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(); 

答案 2 :(得分:0)

你无法用millis做到这一点,因为你需要知道日界的下落(即午夜)。午夜两边的一毫秒意味着两个不同的日子。

您需要使用日历来确定两个日期之间的天数。 JodaTime库对此类计算有很多额外的支持。

另见Calculating the difference between two Java date instances

答案 3 :(得分:0)

你只是想找到天数,对吧?

尝试查看this,它可能有您想要的内容。

答案 4 :(得分:0)

我之前制作了这个代码,它可以帮助你

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);
    }
}

答案 5 :(得分:0)

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.");
    }
} 

答案 6 :(得分:0)

Re-post

有一个简单的解决方案,至少对我来说,是唯一可行的解​​决方案。

问题是我看到的所有答案都被抛到了 - 使用Joda,或Calendar,或者其他什么 - 只需要考虑毫秒数。他们最终计算两个日期之间的 24小时循环次数,而不是实际天数。所以从1月1日晚上11点到1月2日凌晨1点将返回0天。

要计算startDateendDate之间的实际天数,只需执行以下操作:

// 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;

这将在1月2日到1月1日之间返回“1”。如果您需要计算结束日期,只需在daysBetween中添加1(我需要在我的代码中执行此操作,因为我想计算范围内的总天数)。