1

我必须计算两个日期之间的差异。这是我的代码:

        System.out.println("date1  "+date1);
        System.out.println("date2  "+date2);

        totalDifference=date2.getSeconds()-date1.getSeconds();

        System.out.println("Total Difference is"+totalDifference);

我面临的问题是结果为0:

 09-24 17:24:53.839: I/System.out(9317): date1  Wed Aug 15 00:00:00 GMT+05:30 2012
 09-24 17:24:53.839: I/System.out(9317): date2  Mon Sep 24 17:24:00 GMT+05:30 2012
 09-24 17:24:53.839: I/System.out(9317): Total Difference is 0

我做错了什么?

感谢大家的解决方案和其他宝贵的资源,也请帮助我解决这个问题。 嘿,假设如果我输入 31st Aug 23:59:00 和下一个日期 1 September 00:02:00 ,我需要将记录显示为 1 天。请帮我做这个

4

5 回答 5

1

getSeconds() 返回日期的第二个,所以在你的例子中,

日期 1 星期三 8 月 15 日 00:00:00 GMT + 05:30 2012

日期 2 周一 9 月 24 日 17:24:00 GMT + 05:30 2012

在这两种情况下,日期的第二个都是 0。如果你想要差异,你有一个例子

Android/Java - 以天为单位的日期差异

于 2012-09-24T12:09:33.000 回答
1

date.getSeconds()方法返回该日期对象中的秒数。

在您的情况下,两个日期都有 00 秒,因此差异为 0。

您将不得不使用date.getTime().

于 2012-09-24T12:03:29.940 回答
0

Just see the code below an make small changes according to you.

package com.datediff;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class DateDiffActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

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

    Calendar today = Calendar.getInstance();

    long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); 

    Toast.makeText(getApplicationContext(), diff+"", Toast.LENGTH_LONG).show();

    }
}
于 2012-09-25T10:00:46.233 回答
0

此处给出了此方案的最佳示例。它包含类似的东西

Calendar calendar1 = Calendar.getInstance();
  Calendar calendar2 = Calendar.getInstance();
  calendar1.set(2007, 01, 10);
  calendar2.set(2007, 07, 01);
  long milliseconds1 = calendar1.getTimeInMillis();
  long milliseconds2 = calendar2.getTimeInMillis();
  long diff = milliseconds2 - milliseconds1;
  long diffSeconds = diff / 1000;
  long diffMinutes = diff / (60 * 1000);
  long diffHours = diff / (60 * 60 * 1000);
  long diffDays = diff / (24 * 60 * 60 * 1000);
  System.out.println("\nThe Date Different Example");
  System.out.println("Time in milliseconds: " + diff
 + " milliseconds.");
  System.out.println("Time in seconds: " + diffSeconds
 + " seconds.");
  System.out.println("Time in minutes: " + diffMinutes 
+ " minutes.");
  System.out.println("Time in hours: " + diffHours 
+ " hours.");
  System.out.println("Time in days: " + diffDays 
+ " days.");

最初尝试用谷歌搜索你的问题:)

于 2012-09-24T12:08:44.597 回答
0

您可以使用getTime()方法 onjava.util.Date以毫秒为单位获取日期,并使用它来找出两个java.util.Date变量之间的差异,以获得更精确的差异。

于 2012-09-24T12:03:40.903 回答