java - 如何编写 Java 代码来获取用户输入的任何日期,并列出接下来的 40 天?

标签 java string date

我试图确保我的 nextday 方法可以在用户输入的日期中添加一天,并确保它正确添加 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.

最佳答案

  • 您应该使用java.text.DateFormat来解析日期字符串
  • 编写自己的日期算术非常容易出错(闰年只是众多异常(exception)之一),最好使用 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);
}

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

关于java - 如何编写 Java 代码来获取用户输入的任何日期,并列出接下来的 40 天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18986083/

相关文章:

java - "Could not find the main class: XX. Program will exit."

java - 从 Jenkins(Maven 项目)执行 TestNG.xml

r - 如何在R中找到日期的 "origin"

MySQL奇怪的date_add间隔

c++ - 将字符串从字符串流移动到字符串 vector 中

sql - sql中如何对每个日期的数据进行分类?

java - @KafkaListener 正常关闭,批处理 Kakfa 监听器不工作

java - list 合并失败: Attribute application@appComponentFactory cant solve this

c++ - 从 char 数组获取从起始索引到结束的字符串

c# - 使用混合语言(LTR + RTL)重新排列字符串?