2017-09-30 101 views
0

我必須創建一個打印日期列表(年,月,日)直到用戶選擇日期(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。

問題:

  1. 添加日曆類型元素融入到一個列表
  2. 打印清單。另外在打印過程中
  3. 格式化日期列表

當我嘗試打印,輸出只是一堆同日重複的。

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]]

+2

我不能更強烈地建議你避免遺留'java.util.Calendar'類。你應該在'java.time'包中找到適合你的用例的類。 –

+0

'日曆'具有'之前'和'之後'以進行比較的方法 –

+1

「java.time'包中的大多數(如果不是全部)類實現」Comparable「。 –

回答

0

第一個問題是你打印出結果的方式:

System.out.println(Arrays.toString(dates.toArray())); 

如果你想格式化的日期,您將需要使用格式化程序。

private static SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd"); 

static private void printListOfDates(List<Calendar> dates){ 
    for (Calendar date : dates) { 
     System.out.println(outputFormat.format(date)); 
    } 
} 

第二個問題是,您似乎在getListOfDates的循環中重複使用了相同的temp_cal對象。這會導致您的列表包含同一個Calendar對象的多個副本(多次修改)。您需要爲循環中的每個迭代創建一個新實例。

2

我不知道,如果這是你的正確的格式(我將離開這個作爲你一個任務),但你可以用做這樣的事情LocalDate

import java.util.Scanner; 
import java.time.LocalDate; 
import java.time.format.DateTimeFormatter; 

class Main { 
    public static void main(String[] args) { 
    Scanner scanner = new Scanner(System.in); 

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); 
    LocalDate endDate; 

    while(true){ 
     System.out.print("Enter the endDate in the format of yyyy/MM/dd:"); 
     String date = scanner.next(); 
     try { 
     endDate = LocalDate.parse(date, formatter); 
     break; 
     } catch (Exception e) { 
     System.err.println("ERROR: Please input the date in the correct format"); 
     } 
    } 

    System.out.println("Below are the days between the current day and " + endDate); 
    printDaysBetween(endDate); 
    } 

    public static void printDaysBetween(LocalDate end){ 
    LocalDate start = LocalDate.now(); 
    while (!start.isAfter(end)) { 
     System.out.println(start); 
     start = start.plusDays(7); 
    } 
    } 
} 

使用示例:

Enter the endDate in the format of yyyy/MM/dd: 2017-10-30 
ERROR: Please input the date in the correct format 
Enter the endDate in the format of yyyy/MM/dd: 2017/10/30 
Below are the days between the current day and 2017-10-30 
2017-09-30 
2017-10-07 
2017-10-14 
2017-10-21 
2017-10-28 
0
import java.util.Date; 
import java.time.*; 
import java.text.SimpleDateFormat; 
import java.util.*; 
public class days 
{ 
public static void main (String args[]){ 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter Dates (Start(yyyy/mm/dd)-End)"); 
    //example 2017 1 5 -> 5 jan 2017 
    getDates(Integer.parseInt(input.next()),Integer.parseInt(input.next()), 
       Integer.parseInt(input.next()),Integer.parseInt(input.next()), 
        Integer.parseInt(input.next()),Integer.parseInt(input.next())); 
    /*the input needed example 
    * 2017 
    * 1 
    * 1  -Start date 
    * 2017 
    * 2 
    * 10  -End date 
    */ 

} 

public static void getDates(int pYearStart, int pMonthStart, int pDayStart, 
            int pYearEnd, int pMonthEnd, int pDayEnd){ 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd"); 
    int year = pYearStart; 
    int month = pMonthStart-1; 
    int day = pDayStart; 
    Calendar start = new GregorianCalendar(year,month,day); 
    int yearEnd = pYearEnd; 
    int monthEnd = pMonthEnd-1; 
    int dayEnd = pDayEnd; 
    Calendar end = new GregorianCalendar(yearEnd,monthEnd,dayEnd); 
    System.out.print("Start Date: "); 
    System.out.println(sdf.format(start.getTime())); 

    System.out.print("End Date: "); 
    System.out.println(sdf.format(end.getTime())); 

    System.out.println(""); 
    System.out.println("All Dates:"); 

    boolean sameDate = false; 
    int amount = 0; 
    do{ 

     System.out.println(sdf.format(start.getTime())); 
     start.add(Calendar.DAY_OF_MONTH, 7); 
     amount++; 
     if(start.get(Calendar.DAY_OF_MONTH) >= end.get(Calendar.DAY_OF_MONTH) && 
     start.get(Calendar.MONTH) == end.get(Calendar.MONTH)) { 
      sameDate = true;} 
    }while(sameDate != true); 
    System.out.println("No of dates: "+amount); 
    } 
} 

我覺得這是你想要的,我沒有使用一個列表,但瓚什麼只要你喜歡就可以。