簡體   English   中英

計算未來N天即將到來的生日的方法

[英]Method to calculate the upcoming birthdays in next N days

我需要一個采用整數輸入(N)並在接下來的N天返回生日的方法。 我發現很難運行任何代碼。 下面只是我希望它如何工作的代碼-絕不是工作代碼。 非常感謝您的幫助。

/* print out all the birthdays in the next N days */
public void show( int N){
    Calendar cal = Calendar.getInstance();
    Date today = cal.getTime();

    // birthdayList is the list containing a list 
    // of birthdays Format: 12/10/1964 (MM/DD/YYYY)

    for(int i = 0; i<birthdayList.getSize(); i++){
        if(birthdayList[i].getTime()- today.getTime()/(1000 * 60 * 60 * 24) == N)){
            System.out.println(birthdayList[i]);
        }
    }

}
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTime(new Date());
calendar.add(Calendar.DATE, n); // n is the number of days upto which to be calculated
Date futureDate = calendar.getTime();
List<String> listOfDates = returnListOfDatesBetweenTwoDates(new Date()
                                                                , futureDate);

哪里

public static List<String> returnListOfDatesBetweenTwoDates(java.util.Date fromDate,
                                                             java.util.Date toDate) {
    List<String> listOfDates = Lists.newArrayList();
    Calendar startCal = Calendar.getInstance(Locale.ENGLISH);
    startCal.setTime(fromDate);
    Calendar endCal = Calendar.getInstance(Locale.ENGLISH);
    endCal.setTime(toDate);
    while (startCal.getTimeInMillis() <= endCal.getTimeInMillis()){
        java.util.Date date = startCal.getTime();
        listOfDates.add(new SimpleDateFormat("dd-MM-yyyy"
                                               , Locale.ENGLISH).format(date).trim());
        startCal.add(Calendar.DATE, 1);
    }
    return listOfDates;
}

現在,將此日期列表與您的生日日期列表進行比較,並進行相應的工作

搜索StackOverflow

簡短的回答,因為在StackOverflow上已經解決了數百次(甚至數千次)這種工作。 請搜索StackOverflow以獲取更多信息。 搜索“ joda”和“半開”,甚至“不可變”。 並且顯然搜索下面示例代碼中看到的類和方法名稱。

避免使用java.util.Date和.Calendar

避免與Java捆綁在一起的java.util.Date和.Calendar類。 他們出了名的麻煩。 在Java 8中使用Joda-Time或新的java.time包。

喬達時代

假設您的列表包含java.util.Date對象,請將其轉換為Joda-Time DateTime對象。

// birthDates is a list of java.util.Date objects.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( timeZone );
Interval future = new Interval( now, now.plusDays( 90 ).withTimeAtStartOfDay() ); // Or perhaps .plusMonths( 3 ) depending on your business rules.
List<DateTime> list = new ArrayList<>();
for( java.util.Date date : birthDates ) {
    DateTime dateTime = new DateTime( date, timeZone ); // Convert from java.util.Date to Joda-Time DateTime.
    If( future.contains( dateTime ) ) {
        list.add( dateTime );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM