I am trying to pass a date time string in form of yyyy-mm-dd but I am getting this error:
DateDemo.java:9: error: incompatible types: String cannot be converted to Date
DateDemo test = new DateDemo("2021-12-11");
Also, should Boolean be capitalized or lowercased?
import java.util.Date;
public class DateDemo {
private Date start_date;
private Boolean status;
public DateDemo(Date start_date) {
this.start_date = start_date;
}
public static void main(String args[]) {
DateDemo test = new DateDemo("2021-12-11");
}
}
CodePudding user response:
You have a type mismatch issue. String
<> Date
. You should convert you input to the appropriate type for the constructor.
Since it's now 2021, we all should have moved beyond java.util.Date
and embraced java.time
instead
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateDemo {
private LocalDate startDate;
private Boolean status;
public DateDemo(LocalDate startDate) {
this.startDate = startDate;
}
public static void main(String args[]) {
DateDemo test = new DateDemo(LocalDate.parse("2021-12-11", DateTimeFormatter.ISO_DATE));
}
}
Have a look at the Date Time trail for more details
CodePudding user response:
Your constructor has a single argument of type Date
public DateDemo(Date start_date){...}
yet you are passing a String argument to it in your main method
DateDemo test = new DateDemo("2021-12-11");
Try this: DateDemo test = new DateDemo(DateFormat.parse("A VALID DATE STRING HERE"));