【问题标题】:How to write Java code to take any date user inputs, and list the next 40 days?如何编写 Java 代码以获取用户输入的任何日期,并列出接下来的 40 天?
【发布时间】:2013-09-24 15:38:44
【问题描述】:

我正在尝试确保我的 nextday 方法可以在用户输入的日期上添加 1 天,并确保它正确添加 40 天,同时考虑到每月正确的天数和闰年

public nextday() {
    for (int count = 1; count < 40; count++)
        ;
}

public String toDayDateString() // toDayDateString method {
    int countDays = 0;

    for (int i = 1; i < getMonth(); i++) {
        if (i == 2 && checkLeapYr(getYear()))
            countDays += 29;
        else
            countDays += daysPerMonth[i];
    }
    countDays += date;
    String message = String.format("\n", countDays, getYear());
    return message;
}

private Boolean checkLeapYr(int inYear) { // check leap year method.
    if (getYear() % 400 == 0 || (getYear() % 4 == 0 && getYear() % 100 != 0))
        return true;
    else
        return false;
}

下面是一个菜单,应该允许用户选择输入日期或退出,但日期没有被正确接受。

{
 public static void main ( String [] args)
// User selects how they will enter the dates
 {      
   +"(1) Enter the date as MM/DD/YYYY\n"
   +"(Any Key) Quit\n";
  int input=0;

  Date newDate;

  do{
   String userInput = JOptionPane.showInputDialog(null, menu);
   input = Integer.parseInt( userInput);
   String outputMessage="";

   if ( input = 1)
   {
    userInput =JOptionPane.showInputDialog(null, "Please enter a date as 02/28/2011");

    switch ( input )  // here is where the menu choice will be evaluated
    {
     case 1 :
      token = userInput.split("/");
      if (token.length == 3 )

      {
       newDate = new Date( Integer.parseInt( token[0]),
        Integer.parseInt( token[1]), Integer.parseInt( token[2]) );
       outputMessage = newDate.toString();
       JOptionPane.showMessageDialog(null, outputMessage);
      }

      break;

     case 2:
  } while ( input <>1); // this will quit the program when user selects any key other than 1 at the menu.

【问题讨论】:

  • 顺便说一句,if (input = 1) 不会做你认为的那样,“不等于”是!=
  • 看看Calendar 类。它有你需要的一切。
  • 不要重新发明轮子。您可以使用 java.util.Calendar API(它有点麻烦,但可以使用)或 Joda Time API。查看此问题的答案:stackoverflow.com/questions/428918/…

标签: java string date


【解决方案1】:
  • 您应该使用java.text.DateFormat 来解析日期字符串
  • 编写自己的日期算术非常容易出错(闰年只是众多例外之一),最好改用java.util.Calendar 实现。

至于日期算术,下面是使用Calendar 的方法:

//TODO: parse input string with DateFormat
Date startDate = ... // your parsed date

Calendar cal = new GregorianCalendar();
cal.setTime(startDate);

for (int i = 0; i < 40; i++) {

    // add a day
    cal.add(Calendar.DATE, 1);

    // and get the new result as date
    Date date = cal.getTime();

    System.out.println(date);
}

如果您需要倒数,请添加负数时间量(天、小时等)。

【讨论】:

    【解决方案2】:
        public static void main(String[] args) throws IOException, ParseException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter date(dd/mm/yyyy) : ");
        String input = br.readLine();
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
        Calendar cal = Calendar.getInstance();
        Date date = df.parse(input);
        cal.setTime(date);
        cal.add(Calendar.MONTH, 1); // to get actual month,as it parses 02 as Jan.
        for (int i = 1; i < 40; i++) {
            System.out.println(" day " + i + " : " + cal.getTime());
            cal.add(Calendar.DATE, 1);
        }
    }
    

    【讨论】:

      【解决方案3】:
          public static void main(String[] args) throws IOException,ParseException{
                      BufferedReader br = new BufferedReader(new   InputStreamReader(System.in));       
                      System.out.print("Enter date(dd/mm/yyyy) : ");
                      String input = br.readLine();
                      DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                      Calendar cal = Calendar.getInstance();
                      Date date = df.parse(input);
                      cal.setTime(date);
                      for (int i = 1; i <=40; i++) {
                          cal.add(Calendar.DATE,1);
                          System.out.println(" day " + i + " : " + cal
      
      .getTime());
      
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多