0

您好我有一个字符串 [] 数组,其中包含格式为 YYYY/MM/DD 的日期。我想遍历这个数组,看看数组中接下来的 2 个元素是否包含连续的日期。如果他们这样做,那么只需增加计数变量。这是我到目前为止所拥有的。我基本上只需要关于检查是否有 3 个连续日期的 if 语句的帮助。

int count = 0;

String[] dates = { 
        "2004/1/23", "2004/1/24", "2004/1/25",
        "2004/1/26", "2004/1/29", "2004/2/11", 
        "2004/2/17", "2004/2/18", "2004/2/18", "2004/3/7"};

for(int i = 0; i < dates.length-2; i++){

    //Help needed here! If i, i+1 and i+2 are consecutive...
    if(...){
        count++;
    }
}

我意识到我可能需要先将字符串日期转换为实际的 Date 对象,然后才能比较它们。进一步的指导将不胜感激。谢谢

4

4 回答 4

6

转换String[]Date[](即准备一个Date数组)。我想你已经知道如何做到这一点了。

现在您可以使用以下方式检查连续日期:

Calendar c = Calendar.getInstance();
int numConsecutive = 0;
Date last = null;

for (int i = 0; i < dates.length; i++) {
    c.setTime(dates[i]);
    c.add(Calendar.DATE, -1);
    if (c.getTime().equals(last)) {
        numConsecutive++;
    } else {
        numConsecutive = 0;
    }
    if (numConsecutive == 2) {
        numConsecutive = 0;
        count++;
    }
    last = dates[i];
}
于 2013-03-04T21:27:09.303 回答
2
于 2017-06-06T01:49:22.790 回答
0

您好,您需要计算两个日期之间的秒数,然后转换为天数:

import java.util.*;  
class DateDiff  
{  
    public static void main(String [] args)  
    {  
        Calendar c1=Calendar.getInstance();  
        c1.set(2011,5, 29 );  
        Calendar c2=Calendar.getInstance();  
        c2.set(2012,5,30);  

        Date d1=c1.getTime();  
        Date d2=c2.getTime();  

        long diff=d2.getTime()-d1.getTime();  
        int noofdays=(int)(diff/(1000*24*60*60));  
        System.out.println(noofdays);  
    }  
}  
于 2013-03-04T21:17:07.500 回答
0
@Test
public void threeConsecutiveDates() throws ParseException {
    List<Date> consecutive = new ArrayList<>();
    consecutive.add(new Date(0));
    final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

    String[] dates = {
            "2004/1/23", "2004/1/24", "2004/1/25",
            "2004/1/26", "2004/1/29", "2004/2/11",
            "2004/2/17", "2004/2/18", "2004/2/18", "2004/3/7"};
    for (String s : dates) {
        Date previous = consecutive.get(consecutive.size()-1);
        Date current = format.parse(s);
        if(previous.before(current) && (current.getTime()-previous.getTime() == 1000 * 60 * 60 * 24)) {
            consecutive.add(current);
        } else {
            consecutive.clear();
            consecutive.add(current);
        }
        if(consecutive.size() == 3) {
            break;
        }
    }
    System.out.println("consecutive = " + consecutive);
}
于 2013-03-04T21:34:41.247 回答