大约两天之间的日子

时间:2015-03-11 06:20:49

标签: java date

在尝试计算两个日期之间的天数时,我注意到波纹管代码中的错误。 2月份没有权利,

这是代码,

public class NewClass {

    public int numberOfDays(String fromDate,String toDate)
    {    
   java.util.Calendar cal1 = new java.util.GregorianCalendar();
   java.util.Calendar cal2 = new java.util.GregorianCalendar();


   StringBuffer sBuffer = new StringBuffer(fromDate);


   String yearFrom = sBuffer.substring(6,10);
   String monFrom = sBuffer.substring(0,2);
   String ddFrom = sBuffer.substring(3,5);



   int intYearFrom = Integer.parseInt(yearFrom);
   int intMonFrom = Integer.parseInt(monFrom);
   int intDdFrom = Integer.parseInt(ddFrom);


   cal1.set(intYearFrom, intMonFrom, intDdFrom);


   StringBuffer sBuffer1 = new StringBuffer(toDate);


   String yearTo = sBuffer1.substring(6,10);
   String monTo = sBuffer1.substring(0,2);
   String ddTo = sBuffer1.substring(3,5);


   int intYearTo = Integer.parseInt(yearTo);
   int intMonTo = Integer.parseInt(monTo);
   int intDdTo = Integer.parseInt(ddTo);


   cal2.set(intYearTo, intMonTo, intDdTo);

   int days = daysBetween(cal1.getTime(),cal2.getTime());
   return days;
     }


      public int daysBetween(Date d1, Date d2)
      {

  return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
   }


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

      String s1 = "02-28-2015"; 
      String s2 = "03-01-2015";

       int num=numberOfDays(s1, s2);
       System.out.println(num);

}

 }

如果我们给出varialbe s1和s2的上述日期,结果是4.但答案是错误的 因为2015年2月只有28天。

我认为问题是这个功能部分(1000 * 60 * 60 * 24)

如果有人知道如何处理此问题,请更新此代码或给我一些帮助!

1 个答案:

答案 0 :(得分:0)

不要尝试使用两次之间的毫秒差来计算差异,只有很多特性与日期/时间计算可能会导致各种错误。

相反,保存自己(很多)时间并使用专用库

Java 8

LocalDate start = LocalDate.of(2015, Month.JANUARY, 1);
LocalDate end = LocalDate.now();

long days = ChronoUnit.DAYS.between(start, end);
System.out.println(days);

哪个输出69

JodaTime

DateTime startDate = new DateTime(2015, DateTimeConstants.JANUARY, 1, 0, 0);
DateTime endDate = new DateTime();

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(days);

哪个输出69