我必須創建一個打印日期列表(年,月,日)直到用戶選擇日期(end_date
後來轉換爲end_cal
)的程序。列表中的日曆類型元素
例如,如果今天是2017-09-30 Saturday
和用戶輸入的日期2017-10-30
,程序必須打印出這些日期:
2017年9月30日,2017年10月7日,2017年10月14日,2017- 10-21,2017-10-28。
問題:
- 添加日曆類型元素融入到一個列表
- 打印清單。另外在打印過程中
- 格式化日期列表
當我嘗試打印,輸出只是一堆同日重複的。
public class Weekdays {
static Scanner input = new Scanner(System.in);
static Calendar temp_cal = Calendar.getInstance(); //temporary calendar object. it's value is being chaged in the process
static Calendar start_cal = Calendar.getInstance(); // current day when the program is executed
static Calendar end_cal = Calendar.getInstance(); //end date that the user inputs
static SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
public static boolean date_validation(String date){ //partial validation: whether the input date is in a correct format
Date test_date;
try {
test_date = format.parse(date);
}catch (ParseException e){
return false;
}
return true;
}
//created list of dates that are of the same day of the week (for example all Sundays)
static private List<Calendar> getListOfDates(){
List<Calendar> dates = new ArrayList<>();
while (!((temp_cal.get(Calendar.YEAR)>= end_cal.get(Calendar.YEAR))&&(temp_cal.get(Calendar.MONTH) >= end_cal.get(Calendar.MONTH))&&(temp_cal.get(Calendar.DAY_OF_YEAR) >= end_cal.get(Calendar.DAY_OF_YEAR))))
{
temp_cal.add(Calendar.DATE, 7);
dates.add(temp_cal); }
return dates;
}
static private void printListOfDates(List<Calendar> dates){
System.out.println(Arrays.toString(dates.toArray()));
}
public static void main(String[] str) throws ParseException{
String end_date = input.next();
while(!(date_validation(end_date))){
end_date = input.next();
}
end_cal.setTime(format.parse(end_date));
printListOfDates(getListOfDates());
}
輸入:2018/01/01
輸出(拷貝只是一個例子,整體輸出是幾個只是這兩份):
java.util.GregorianCalendar中[時間= 1515233525518,areFieldsSet =真,areAllFieldsSet =真,寬大=真,區= sun.util.calendar.ZoneInfo [ID = 「歐洲/赫爾辛基」,偏移= 7200000,dstSavings = 3600000,useDaylight =真,過渡= 118,lastRule = java.util.SimpleTimeZone中[ID =歐洲/赫爾辛基,偏移= 7200000,dstSavings = 3600000,useDaylight =真,startYear = 0,STARTMODE = 2,startMonth = 2,開始天= -1,startDayOfWeek = 1,開始時間= 3600000,startTimeMode = 2,endMode = 2,endMonth = 9,endday指定= -1,一個endDayOfWeek = 1,結束時間= 3600000,endTimeMode = 2]],Firstdayofweek可= 2,minimalDaysInFirstWeek = 4,ERA = 1,YEAR = 2018,MONTH = 0,WEEK_OF_YEAR = 1,WEEK_OF_MONTH = 1,DAY_OF_MONTH = 6,DAY_OF_YEAR = 6,DAY_OF_WEEK = 7,DAY_OF_WEEK_IN_MONTH = 1,AM_PM = 1,HOUR = 0,HOUR_OF_DAY = 12,分= 12,秒= 5,多段微差= 518,ZONE_OFFSET = 7200000,DST_OFFSET = 0]]
我不能更強烈地建議你避免遺留'java.util.Calendar'類。你應該在'java.time'包中找到適合你的用例的類。 –
'日曆'具有'之前'和'之後'以進行比較的方法 –
「java.time'包中的大多數(如果不是全部)類實現」Comparable「。 –