关于两个日期之间的日期 [英] About days between two dates

查看:131
本文介绍了关于两个日期之间的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在两个日期之间计算日期时,我注意到错误代码。

I have noted error in bellow code when trying calculate days between two dates. There isn't right with month February,

这里是代码,

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天。

If we gives above dates for varialbe s1 and s2, result is 4. But answer is wrong because 2015 February has only 28 days.

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

I think problem is this function part (1000 * 60 * 60 * 24)

如果有人知道该怎么做,请更新此代码或给我一些帮助!

If anyone knows what to do with this, please update this code or give me some help!!!

推荐答案

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

Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.

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

Instead, save yourself (alot) of time and use a dedicated library

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

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

哪些输出 69

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

这篇关于关于两个日期之间的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆