如何区分两个日期

时间:2012-09-24 12:00:40

标签: java android

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

        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

我做错了什么?

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

5 个答案:

答案 0 :(得分:1)

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

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

您必须使用date.getTime()

答案 1 :(得分:1)

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

date1 Wed Aug 15 00:00: 00 GMT + 05:30 2012

date2 Mon Sep 24 17:24: 00 GMT + 05:30 2012

在这两种情况下,日期的第二个为0.如果你想要差异,你可以在

中找到一个例子

Android/Java - Date Difference in days

答案 2 :(得分:0)

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

答案 3 :(得分:0)

此方案的最佳示例是here。它包含类似

的内容
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.");

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

答案 4 :(得分:0)

根据您的要求,只需查看下面的代码即可进行细微更改。

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

    }
}