我被困在工作中,我該如何檢查連續6天?如何從指定日期連續檢查6天?
例如:
如果指定日期:01/01/2011
,我想從01/01/2011從可用日期列表檢查連續6天。 在連續發現一天之後,它應該繼續下一個在列表中可用的連續鏈。
並追蹤連續6天的查找時間和時間?
如果任何人能幫助我,這將是對我很大的幫助...提前
感謝。
我被困在工作中,我該如何檢查連續6天?如何從指定日期連續檢查6天?
例如:
如果指定日期:01/01/2011
,我想從01/01/2011從可用日期列表檢查連續6天。 在連續發現一天之後,它應該繼續下一個在列表中可用的連續鏈。
並追蹤連續6天的查找時間和時間?
如果任何人能幫助我,這將是對我很大的幫助...提前
感謝。
排序的日期列表然後用你的邏輯
List<Date> dateList = new ArrayList<Date>();
//add your dates here
Collections.sort(dateList);
int count = 0;
Date previousDate = null;
List<Date> datesGroup = new ArrayList<Date>();
for (Date date : dateList) {
if (previousDate == null) {
previousDate = new Date();
count++;
} else {
long diff = date.getTime() - previousDate.getTime();
if (diff == 86400000) {
count++;
} else {
count = 0;
datesGroup.clear();
}
}
datesGroup.add(date);
previousDate.setTime(date.getTime());
if (count == 6) {
break;
}
}
for (Date dates : datesGroup) {
System.out.println("dates sorted : " + dates);
}
這段代碼讓你在天兩個日期之間的區別:
import java.util.*;
public class DateDifference {
public static void main(String args[]){
DateDifference difference = new DateDifference();
}
DateDifference() {
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
cal1.set(2008, 8, 1);
cal2.set(2008, 9, 31);
System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
}
public int daysBetween(Date d1, Date d2){
return (int)((d2.getTime() - d1.getTime())/(1000 * 60 * 60 * 24));
}
}
你應該沒有問題,在它納入你的代碼,以便它你需要什麼。代碼取自here。
Calendar lowerCal = Calendar.getInstance();
lowerCal.set(Calendar.MONTH, 0);
lowerCal.set(Calendar.DATE, 1);
lowerCal.set(Calendar.YEAR, 2011);
//set other param 0
Calendar higherCal = Calendar.getInstance();
higherCal.set(Calendar.MONTH, 0);
higherCal.set(Calendar.DATE, 1);
higherCal.set(Calendar.YEAR, 2011);
higherCal.add(Calendar.DATE, 6);
//set other param 0
Calendar calToCheck = Calendar.getInstance();
if (calToCheck.compareTo(higherCal) <= 0 && calToCheck.compareTo(lowerCal) >= 0){
//YES
}
請參見
正如我在我的評論說,目前還不清楚你的真實意圖 - 但它幾乎一定,使用Joda Time的會讓你的生活比標準庫更容易。這只是一個更好的日期/時間的API,導致更清晰的代碼。
例如,這將遍歷的日期和它後面的6個日期:
LocalDate date = new LocalDate(2010, 1, 1); // January is 1 in Joda. How novel.
for (int i = 0; i < 7; i++)
{
// Do something with date here - check it or whatever
date = date.plusDays(1);
}
你也可以在一個稍微不同的方式寫:
LocalDate start = new LocalDate(2010, 1, 1);
LocalDate end = start.plusDays(7);
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1))
{
// Do something with date here
}
`我<7;`! ,不應該是`我<6;` – 2011-01-13 07:34:09
嗨,喬恩Skeet你的理解是有些什麼不同但我想檢查6弊如果連續六天和第七天都有用戶在場,則第七天將被視爲加班等等,而在可用日期列表中已有enries。 – 2011-01-13 07:44:01
請編輯您的問題以提供樣本輸入和期望的輸出。這會讓你更容易幫助你。例如,如果已知輸入已被排序,則會有所不同。 – 2011-01-13 07:50:02