我正在尝试创建一个日历类,在其中我初始化一个默认日期。当用户创建类时,默认构造函数分配值“01-01-2012”。如果用户输入有效日期作为字符串参数,则第二个构造函数将分配新日期。如果不是,我希望类给出友好警告,这不是有效日期并继续保持默认分配。(例如。如果用户输入“02/31/2012”。这将引发警告并继续创建实例,同时将默认设置为“01-01-2021”。)我还创建了一个设置日期的方法,这样可以一旦他们给出有效日期,稍后再更改。为了做到这一点,我应该如何使用第二个构造函数?还是有更好更有效的流程来做到这一点?
import java.time.*;
import java.time.format.DateTimeFormatter;
public class CalendarDate {
private String date;
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMMM dd uuuu");
//constructor sets date to January 1, 2012
CalendarDate(){
date = "01-01-2012";
};
/**
* Initializes object's chosen date
*
* @param day - initializes day
* @param month - initialazes month
* @param year - initialazes year
*/
public CalendarDate(String date){
this.date = date;
} // 1 - parameter Constructor
/**
*
* Sets new date given to this object
*
* @param date sets new date to object
*/
public void setDate(String date){
this.date = date;
}
/**
*
* Returns objects set date.
*
* @return Returns set date.
*/
public String getDate(){
LocalDate getDate = LocalDate.parse(date);
String formattedDate = getDate.format(formatter);
return formattedDate;
}
/**
*
* Returns object's date
*
* @return Returns object's date
*/
public String getNextDate(){
LocalDate dateTime = LocalDate.parse(date);
LocalDate returnValue = dateTime.plusDays(1);
String newNextDate = formatter.format(returnValue);
return newNextDate;
}
/**
* Returns prior date from the object's given date.
*
* @return
*/
public String getPriorDate(){
return " ";
}
/**
* Returns the day of the week from the object's given date.
*
* @return
*/
public String getDayOfWeek(){
return " ";
}
}
public class Calendar extends CalendarDate{
public static void main(String[] args){
CalendarDate testDate = new CalendarDate("06-07-1992");
testDate.getDate();
}
}
这是我到目前为止所拥有的,我想使用 LocalDate 和 DateTimeFormatter。任何事情都会有所帮助。