0

我想计算两个日期之间的天数差。当日期的年份没有改变时,我的代码工作正常,但是当我计算两个日期之间的差异时:(13/01/2012 到 13/12/2011),它给出了一个负值。当我计算今天日期和未来日期之间的差异时,它也会给出错误的差异值。请帮我。先感谢您。这是我的代码:

//getting values from text box
String fromtext = from.getText().toString();
String totext = to.getText().toString();
//sdf if a simple date formatter
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date fromdate = (Date) sdf.parse(fromtext);
Date todate = (Date) sdf.parse(totext);

Calendar fromcal = Calendar.getInstance();
Calendar tocal = Calendar.getInstance();


    fromcal.setTime(fromdate);
    tocal.setTime(todate);// setting to date


    int reportDays=(int)(todate.getTime()-fromdate.getTime())/(3600*24*1000);

请告诉我计算天数差异的最佳方法是什么。

4

9 回答 9

6

日期输入 : 13/01/2012,13/12/2011

格式似乎dd/MM/yyyy并且您使用了错误的格式(即MM/dd/yyyy

于 2012-01-13T06:48:57.297 回答
2
于 2017-03-25T10:42:46.657 回答
1

我认为你应该尝试更好的谷歌搜索......

于 2012-01-13T06:51:01.950 回答
1

除了已经提到的格式问题之外,您可能还会遇到溢出。试试这个:

int reportDays=(int)((todate.getTime()-fromdate.getTime())/(3600*24*1000));
于 2012-01-13T06:58:19.557 回答
0

使用 joda time 将是最简单的方法。

于 2012-01-13T06:49:16.500 回答
0

检查此代码:

import java.util.Calendar;

public class DateDifferent{  
  public static void main(String[] args){
  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-01-13T06:51:35.723 回答
0

这是我为此目的编写的一个简单的小类:

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

public class DifferenceInDays
{
    public int dateOffset(String incomingDate) throws ParseException
    {
        // parse dates
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = (Date) formatter.parse(incomingDate);

        // convert to milliseconds
        long millisecs = date.getTime();

        // convert to days
        int offsetInDays = (int) Math.abs(millisecs / (1000 * 60 * 60 * 24));
        return offsetInDays;
    }
}

它使用绝对值方法处理负偏移量。

于 2012-01-13T13:02:52.237 回答
0

如果您使用具有夏令时的语言环境尝试此操作,并且开始日期和结束日期在夏令时更改之前和之后,则结果可能会相差 1 天。这是因为DateCalendar使用时区。

如果您只打算处理 1900 年到 2100 年之间的日期,则有一个简单的计算可​​以为您提供自 1900 年以来的天数:

public static int daysSince1900(Date date) {
    Calendar c = new GregorianCalendar();
    c.setTime(date);

    int year = c.get(Calendar.YEAR);
    if (year < 1900 || year > 2099) {
        throw new IllegalArgumentException("daysSince1900 - Date must be between 1900 and 2099");
    }
    year -= 1900;
    int month = c.get(Calendar.MONTH) + 1;
    int days = c.get(Calendar.DAY_OF_MONTH);

    if (month < 3) {
        month += 12;
        year--;
    }
    int yearDays = (int) (year * 365.25);
    int monthDays = (int) ((month + 1) * 30.61);

    return (yearDays + monthDays + days - 63);
}

因此,要获得两个日期之间的天数差异,您可以计算它们自 1900 年以来的天数并计算差异。我们的 daysBetween 方法如下所示:

public static Integer getDaysBetween(Date date1, Date date2) {
    if (date1 == null || date2 == null) {
        return null;
    }

    int days1 = daysSince1900(date1);
    int days2 = daysSince1900(date2);

    if (days1 < days2) {
        return days2 - days1;
    } else {
        return days1 - days2;
    }
}

不要问我这个计算是从哪里来的,因为我们从 90 年代初就开始使用它。

于 2012-03-07T02:00:44.790 回答
0

我会这样做!

package javaapplication2;
//@author Ibrahim Yesilay
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JavaApplication2 {  


    public static void main(String[] args) throws ParseException {



    Scanner scan = new Scanner(System.in);        
        System.out.println("First dates Day :");
        int d = scan.nextInt();
        System.out.println("First dates Mounth :");
        int m = scan.nextInt();
        System.out.println("First dates Year :");
        int y = scan.nextInt();
        String date;
        date = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);  
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date firstdate = null;
        firstdate = dateFormat.parse(date);
        System.out.println(dateFormat.format(firstdate)); 

        System.out.println("Second dates Day :");
        d = scan.nextInt();
        System.out.println("Second dates Month :");
        m = scan.nextInt();
        System.out.println("Second dates Year :");
        y = scan.nextInt();
        date = Integer.toString(d) + "/" + Integer.toString(m) + "/" + Integer.toString(y);  
        Date seconddate = null;
        seconddate = dateFormat.parse(date);
        System.out.println(dateFormat.format(seconddate)); 

        if (seconddate.getTime() > firstdate.getTime()) {
            long sonuc = (long)(seconddate.getTime()- firstdate.getTime())/(3600*24*1000);
            System.out.println("" + sonuc);
        } else if (firstdate.getTime() > seconddate.getTime()) {
            long sonuc = (long)(firstdate.getTime()- seconddate.getTime())/(3600*24*1000);
            System.out.println("" + sonuc);
        } else {
            System.out.println("The dates are equal!");
        }

    }   
}
于 2019-06-14T16:22:47.733 回答