如何检查日期数组从今天开始是连续的? [英] How to check array of dates are consecutive from todays date?

查看:125
本文介绍了如何检查日期数组从今天开始是连续的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次用户完成一项任务时,我都会得到一系列唯一的日期。我想检查数组中的日期是否连续,包括今天的日期。

I have an array of unique dates from each time the user completes a task. I want to check if the dates within the array are consecutive from and including todays date.

如果数组包含日期: 2017/6/2,2017/6/3,2017/6/4,2017/6 / 5 ,然后根据今天的日期为 2017/6/5 ,该函数将返回 4 ,因为从今天起(包括今天)有4个连续日期。

If the array contains dates: "2017/6/2, 2017/6/3, 2017/6/4, 2017/6/5" then based on today's date being 2017/6/5 the function would return 4 as there are 4 consecutive dates from and including today.

如果数组包含日期 2017/6/2,2017/6/3 ,2017/6/4 ,则它将返回 0 ,因为数组不包含今天的日期。否则,该计数将在不连续的日期被破坏。

If the array contains dates "2017/6/2, 2017/6/3, 2017/6/4" then it would return 0 as the array does not include today's date. Otherwise the count would be broken upon a non consecutive date.

List<Date> dateList = new ArrayList<Date>();
int count = 0;
Date todayDate = new Date();

for (int i=0; i<dateList.size(); i++){
    // Check if dates within the array are consecutive from todayDate, if so then increment count by 1.
}


推荐答案

如果您使用的是 Java 8 ,请考虑使用新的java.time API 。与旧的API相比,更少的错误和更少的错误

If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

如果您使用的是 Java< = 7 ,则可以使用 ThreeTen Backport ,这是Java 8的新日期/时间类的绝佳反向端口。对于 Android ,有 ThreeTenABP (有关如何使用它的更多信息< a href = https://stackoverflow.com/a/38922755/7605325>此处)。

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

尽管您也可以使用JodaTime ,它已经停产并被新的API取代,我不建议您使用joda启动新项目。即使在 joda的网站中,它也会说:请注意,Joda-Time被认为是一个完成的项目。没有计划进行重大增强。如果使用Java SE 8,请迁移到java.time(JSR-310)。

Although you can also use JodaTime, it's being discontinued and replaced by the new APIs, do I don't recommend start a new project with joda. Even in joda's website it says: "Note that Joda-Time is considered to be a largely "finished" project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".

由于您只想比较日期(日/月/年)而不是时间(小时/分钟/秒),因此最好的选择是使用 LocalDate 类。对于Java 8,此类位于 java.time 包中,而在ThreeTen Backport中,该包位于 org.threeten.bp 。但是类和方法的名称是相同的。

As you want to compare just the date (day/month/year), and not the time (hour/minute/second), the best choice is to use the LocalDate class. For java 8, this class is in java.time package, and in ThreeTen Backport, the package is org.threeten.bp. But the classes and methods names are the same.

代码如下:

public int count(List<LocalDate> dateList, LocalDate today) {
    if (!dateList.contains(today)) { // today is not in the list, return 0
        return 0;
    }

    int count = 0;
    LocalDate prev = dateList.get(0); // get first date from list
    for (int i = 1; i < dateList.size(); i++) {
        LocalDate next = dateList.get(i);
        if (prev.plusDays(1).equals(next)) {
            // difference between dates is one day
            count++;
        } else {
            // difference between dates is not 1
            // Do what? return 0? throw exception?
        }
        prev = next;
    }

    return count + 1; // didn't count the first element, adding 1
}

测试此方法:

List<LocalDate> dateList = new ArrayList<>();
dateList.add(LocalDate.of(2017, 6, 2));
dateList.add(LocalDate.of(2017, 6, 3));
dateList.add(LocalDate.of(2017, 6, 4));
dateList.add(LocalDate.of(2017, 6, 5));
LocalDate today = LocalDate.now();

System.out.println(count(dateList, today)); // 4

另一个测试(今天不在列表中)

Another test (when today is not in the list)

List<LocalDate> dateList = new ArrayList<>();
dateList.add(LocalDate.of(2017, 6, 2));
dateList.add(LocalDate.of(2017, 6, 3));
dateList.add(LocalDate.of(2017, 6, 4));
LocalDate today = LocalDate.now();

System.out.println(count(dateList, today)); // 0






注意:


  • 由于没有指定当日期不连续时该怎么做(返回 0 或引发异常),我对此部分发表了评论。但是,如果要将 java.util.Date 转换为<$,那么将其添加到代码中应该很简单

  • code> LocalDate ,您可以执行以下操作(使用代码答案,如果您有任何疑问,请在此链接中进行完整说明):

  • As it wasn't specified what to do when the days are not consecutive (return 0 or throw exception), I left this part commented. But it should be straightforward to add this to the code
  • If you want to convert java.util.Date to LocalDate, you can do as follows (using the code of this answer, full explanation is in this link in case you have any questions):

public LocalDate convert(Date date) {
    return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}

// if your Date has no toInstant method, try this:
public LocalDate convert(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}


  • 我知道您要检查连续天(因此,日期之间相差1天)。但是,如果您想检查上一个日期是否在下一个日期之前(无论多少天),可以更改 if(prev.plusDays(1).equals( next)) if(prev.isBefore(next))

  • I understood that you want to check for consecutive days (so, a 1-day difference between the dates). But if you want to check if the previous date is before the next (no matter how many days), you can change the if (prev.plusDays(1).equals(next)) to if (prev.isBefore(next))

    我不确定是否是这种情况,但是如果您愿意,还可以将 String 解析为 LocalDate (因此您无需创建许多 Date 对象),使用 DateTimeFormatter

    I'm not sure if that's the case, but if you want, you can also parse a String directly to a LocalDate (so you don't need to create lots of Date objects), using a DateTimeFormatter:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d");
    LocalDate d = LocalDate.parse("2017/6/2", formatter); // 2017-06-02
    


  • 这篇关于如何检查日期数组从今天开始是连续的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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