因此,该程序将用户输入作为格式为“m/d/yyyy”或“mm/dd/yyyy”的字符串。然后它将月份显示为一个单词(例如,month 1 变为“January”)。我需要做的最后一件事是使用 GregorianCalendar 类来确定日期在一年中的序数位置。我真的不知道该怎么做。任何帮助将不胜感激。
import javax.swing.*;
import java.text.*;
import java.util.*;
public class ConvertDate {
public static void main(String[] args) {
String date = "";
String[] monthName =
{"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};
Integer[] daysInMonth = {29, 30, 31};
int mm = 0;
int dd = 0;
int yy = 0;
String month = "";
String day = "";
String year = "";
int maxDay = 0;
while(mm < 1 || mm > 12 || dd < 1 || dd > maxDay) {
date = JOptionPane.showInputDialog(null, "Please, enter a date in the format MM/DD/YYYY.");
String[] partsOfTheDate = date.split("/");
mm = Integer.parseInt(partsOfTheDate[0]);
dd = Integer.parseInt(partsOfTheDate[1]);
yy = Integer.parseInt(partsOfTheDate[2]);
switch (mm) {
case 1: maxDay = daysInMonth[2]; // Jan
break;
case 2: maxDay = daysInMonth[0]; // Feb
break;
case 3: maxDay = daysInMonth[2]; // Mar
break;
case 4: maxDay = daysInMonth[1]; // Apr
break;
case 5: maxDay = daysInMonth[2]; // May
break;
case 6: maxDay = daysInMonth[1]; // Jun
break;
case 7: maxDay = daysInMonth[2]; // Jul
break;
case 8: maxDay = daysInMonth[2]; // Aug
break;
case 9: maxDay = daysInMonth[1]; // Sep
break;
case 10: maxDay = daysInMonth[2]; // Oct
break;
case 11: maxDay = daysInMonth[1]; // Nov
break;
case 12: maxDay = daysInMonth[2]; // Dec
break;
default: maxDay = 0;
break;
}
if((mm < 1 || mm > 12) || (dd < 1 || dd > maxDay)) {
System.out.println("You entered " + date + ";\nyou did not include a valid month, day, or both.");
}
else if((mm > 0 && mm < 13) && (dd > 0 && dd <= maxDay)) {
System.out.println("You entered " + date + ";\nthat can also be expressed as " + monthName[mm - 1] + " " + dd + ", " + yy + ".");
}
GregorianCalendar greg = new GregorianCalendar();
greg.setTime(date);
greg.get(greg.DAY_OF_YEAR);
}
}
}