向日历添加天数

时间:2013-08-12 22:28:23

标签: java date gregorian-calendar

我是这个网站的新手,我刚开始学习Java。我正在尝试将几天添加到GregorianCalendar但它不起作用。这里......(忽略顶部块),它底部的添加日期令人讨厌。

/*
 * Author:Matt M
 * Date:8.12.13
 * Discription: When the user inputs the deadline, and the difficulity of the project, 
 * the program gives the date he should start working on it 
 */
import java.util.*;
public class DeadlinePlanner{
    public static void main(String[] args)
    {
        //take information and restart questions if information is wrong 
        int month = 0, day = 0 ; 
        do
        {
        do
        {
        System.out.println("Input the month please");
        month = (new Scanner(System.in).nextInt() - 1);
        System.out.println("Input the day please");
        day = (new Scanner(System.in).nextInt());

        }
        while (!(month <= 12) || !(month >= 0));
        }
       while (!(day <= 31) || !(month >= 0));

       //Make new calender and initialize it 
       GregorianCalendar setup = new GregorianCalendar();
       setup.set(2013, month, day);
       System.out.println("The deadline is "+ setup.getTime());

       //switch statement to give starting date
       System.out.println("Is the project hard or easy?");
       Scanner difficulity = new Scanner(System.in);

       switch (difficulity.nextLine())
       {

           case "easy":


               setup.add(day, -1);
               System.out.print("The date you should start workinng on is ");
               System.out.println(setup.getTime());
               break;
           case "hard":

               setup.add(day, -10);
               System.out.print("The date you should start workinng on is ");
               System.out.println(setup.getTime());

               break;
           default:
               System.out.println("Your answers to the questions are incorrect");
               break;
       }

    }
}

感谢您阅读本文!我愿意接受任何反馈......

4 个答案:

答案 0 :(得分:19)

这里的代码太多了。用户互动太多。

从一个简单的方法开始做一件事,然后在你做对了之后解决问题。

您可以这样做:

public class DateUtils {
    private DateUtils() {}

    public static Date addDays(Date baseDate, int daysToAdd) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(baseDate);
        calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
        return calendar.getTime();
    }
}

一旦您对此方法进行了测试和验证,您就可以让其他人编写代码来调用它。

更新:四年后,JDK 8为我们提供了新的基于JODA的时间包。您应该使用这些类, JDK 1.0 Calendar

答案 1 :(得分:1)

您需要更改看起来像这样的行:

setup.add(day, -1);
setup.add(day, -10);

setup.add(GregorianCalendar.DAY_OF_MONTH, -1);
setup.add(GregorianCalendar.DAY_OF_MONTH, -10);

有关详细信息,请参阅GregorianCalendar

答案 2 :(得分:1)

阳历有自己的价值,你应该用它来告诉它你在增加什么 你在哪里说

setup.add(day, -1);

你应该使用公历日历值

setup.add(Calendar.DAY_OF_MONTH, -1);

答案 3 :(得分:0)

Calendar c = new GregorianCalendar(2000, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);

有关日历及其字段的更多信息,请访问Calendar

还试着看看过去的帖子: here