【问题标题】:How to get number of days between two dates in java? [duplicate]如何在java中获取两个日期之间的天数? [复制]
【发布时间】:2012-06-18 05:16:30
【问题描述】:

可能重复:
Calculating the Difference Between Two Java Date Instances

如何在 Java 中获取两个日期之间的天数?

最好的方法是什么?这是我得到的,但不是最好的:

public static ConcurrentHashMap<String, String> getWorkingDaysMap(int year, 
    int month, int day){
        int totalworkingdays=0,noofdays=0;
        String nameofday = "";
        ConcurrentHashMap<String,String> workingDaysMap = 
            new ConcurrentHashMap<String,String>();
        Map<String,String> holyDayMap = new LinkedHashMap<String,String>();
        noofdays = findNoOfDays(year,month,day);

        for (int i = 1; i <= noofdays; i++) {
            Date date = (new GregorianCalendar(year,month - 1, i)).getTime();
            // year,month,day
            SimpleDateFormat f = new SimpleDateFormat("EEEE");
            nameofday = f.format(date);

            String daystr="";
            String monthstr="";

            if(i<10)daystr="0";
            if(month<10)monthstr="0";

            String formatedDate = daystr+i+"/"+monthstr+month+"/"+year;

            if(!(nameofday.equals("Saturday") || nameofday.equals("Sunday"))){
                workingDaysMap.put(formatedDate,formatedDate);
                totalworkingdays++;
            }
        }

        return workingDaysMap;
    }

public static int findNoOfDays(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);
        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        return days;
    }

【问题讨论】:

标签: java date


【解决方案1】:

我通常会这样做:

final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;

int diffInDays = (int) ((date1.getTime() - date2.getTime())/ DAY_IN_MILLIS );

不需要外部库,很简单


更新:刚刚看到你也想要“日期”,类似的方法适用:

//assume date1 < date2

List<Date> dateList = new LinkedList<Date>();
for (long t = date1.getTime(); t < date2.getTime() ; t += DAY_IN_MILLIS) {
  dateList.add(new Date(t));
}

当然,使用 JODA time 或其他 lib 可能会让您的生活更轻松一些,尽管我不认为目前的方式难以实现


更新:重要提示! 这仅适用于没有夏令时或类似调整的时区,或者您对“天数差异”的定义实际上意味着“24 小时单位的差异”

【讨论】:

  • 只是提醒使用这种方法的人,这只适用于没有夏令时或类似调整的时区。
  • 我已将答案回滚到原始答案,因为对此答案所做的编辑添加了一些不属于我的原始答案的内容(提到TimeUnit.MILLISECONDS.toDays(date1.getTime() - date2.getTime());)我认为这种编辑是最好将其作为另一个答案而不是更改另一个人的现有答案。
  • 您在这里的第一条评论非常重要。如果date1 出现在夏令时,而date2 出现在非夏令时,这种方法会给出错误的答案。因此,地球上任何实行夏令时的国家都是错误的。
  • @DavidWallace 是的,我会考虑将其作为答案的一部分,以使其更加明显
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多