您面临的问题是日期将以什么格式出现。
你只JTextArea
为他们提供了一个输入值,所以他们可以输入任何东西......
因此,首先,您需要一种可以接受传入值的方法...
public String toDayOfWeek(String date) {
}
从这里您需要将传入的值格式化为Date
String dayOfWeek = null;
try {
Date date = DateFormat.getDateInstance().parse(date);
} catch (ParseException exp) {
dayOfWeek = date + " is an invalid date format";
}
return dayOfWeek;
(显然,以上属于toDayOfWeek(String)
方法)
现在,就个人而言,我会将Date
值传递给另一种方法,但那是因为我疯了......
public String toDayOfWeek(Date date) {
// Now you could extract the various values from the Date object
// but those methods are deprecated...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH); // Months are 0 based
int year = cal.get(Calendar.YEAR);
// Your calculation here...
return yourDayCalculation;
}
但老实说,这样做会更简单,更容易......
public String toDayOfWeek(Date date) {
// Now you could extract the various values from the Date object
// but those methods are deprecated...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return DateFormatSymbols.getInstance().getWeekdays()[cal.get(Calendar.DAY_OF_WEEK)];
}
所以你最终会得到两种方法......
public String toDayOfWeek(String date) {
String dayOfWeek = null;
try {
Date date = DateFormat.getDateInstance().parse(date);
dayOfWeek = toDayOfWeek(date);
} catch (ParseException exp) {
dayOfWeek = date + " is an invalid date format";
}
return dayOfWeek;
}
public String toDayOfWeek(Date date) {
// Now you could extract the various values from the Date object
// but those methods are deprecated...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return DateFormatSymbols.getInstance().getWeekdays()[cal.get(Calendar.DAY_OF_WEEK)];
}