如何编写 Java 代码来接受用户输入的任何日期,并列出接下来的 40 天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18986083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write Java code to take any date user inputs, and list the next 40 days?
提问by Bklyn_40
I am trying to ensure that my nextday method can add ONE day to the date the user entered and ensure it adds 40 days correctly, taking into account the correct days per month and leap years
我试图确保我的 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;
}
Below is a menu that is supposed to allow the user to choose to enter a date or quit, but the date is not being accepted correctly.
下面是一个菜单,应该允许用户选择输入日期或退出,但日期没有被正确接受。
{
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.
回答by Peter Walser
- You should use
java.text.DateFormat
to parse date strings - Writing your own date arithmetic is very error prone (leap years are only one exception among many), better use a
java.util.Calendar
implementation instead.
- 你应该
java.text.DateFormat
用来解析日期字符串 - 编写自己的日期算术非常容易出错(闰年只是众多例外中的一个),最好使用
java.util.Calendar
实现。
As for the date arithmetic, here's how it's done with 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);
}
If you need to count backwards, add negativetime amounts (days, hours etc).
如果您需要倒数,请添加负时间量(天数、小时数等)。
回答by Dax Joshi
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);
}
}
回答by Sandeep Kumar
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());
}
}