我需要一个采用整数输入(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]);
}
}
}
答案 0 :(得分:1)
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;
}
现在将此日期列表与您的生日日期列表进行比较,并相应地进行工作
答案 1 :(得分:1)
简短的回答,因为这种工作已经在StackOverflow上解决了数百次,甚至数千次。请搜索StackOverflow以获取更多信息。搜索&#34; joda&#34;而对于&#34;半开&#34;,也许&#34;不可变&#34;。显然,搜索下面示例代码中的类和方法名称。
避免与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 );
}
}