如何将 LocalDate 转换为字符串形式以便打印出输入的日期
how do I convert LocalDate to String form so it prints out the date inputed
public void displayDVD(DVD dvd) {
if (dvd != null) {
io.print(dvd.getTitle());
io.print(dvd.getReleaseDate());
io.print(dvd.getMpaaRating());
io.print(dvd.getDirectorsName());
io.print(dvd.getStudio());
io.print(dvd.getUserRating());
我需要显示 getReleaseDate,但它告诉我不能,因为它是 LocalDate,不能是字符串。大概是菜鸟的样子,但实在是找不到办法绕过它。提前致谢!
从 Date Time Trail, in particular Parsing and Formatting
开始
类似...
LocalDate ld = LocalDate.now();
System.out.println(ld.format(DateTimeFormatter.ISO_LOCAL_DATE));
打印出来...
2021-11-18
您可以重载 io.print 或将 dvd.getReleaseDate() 转换为字符串。
像这样
private void print(LocalDate localDate) {
System.out.println(localDate.toString());
// use toString() or format
System.out.println(format(localDate));
}
private String format(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return formatter.format(localDate);
}
public void displayDVD(DVD dvd) {
if (dvd != null) {
io.print(dvd.getTitle());
// format
io.print(format(dvd.getReleaseDate()));
io.print(dvd.getMpaaRating());
io.print(dvd.getDirectorsName());
io.print(dvd.getStudio());
io.print(dvd.getUserRating());
}
}
试试这个。
public void displayDVD(DVD dvd) {
if (dvd != null) {
io.print(dvd.getTitle());
io.print(dvd.getReleaseDate().toString());
io.print(dvd.getMpaaRating());
io.print(dvd.getDirectorsName());
io.print(dvd.getStudio());
io.print(dvd.getUserRating());
public void displayDVD(DVD dvd) {
if (dvd != null) {
io.print(dvd.getTitle());
io.print(dvd.getReleaseDate());
io.print(dvd.getMpaaRating());
io.print(dvd.getDirectorsName());
io.print(dvd.getStudio());
io.print(dvd.getUserRating());
我需要显示 getReleaseDate,但它告诉我不能,因为它是 LocalDate,不能是字符串。大概是菜鸟的样子,但实在是找不到办法绕过它。提前致谢!
从 Date Time Trail, in particular Parsing and Formatting
开始类似...
LocalDate ld = LocalDate.now();
System.out.println(ld.format(DateTimeFormatter.ISO_LOCAL_DATE));
打印出来...
2021-11-18
您可以重载 io.print 或将 dvd.getReleaseDate() 转换为字符串。 像这样
private void print(LocalDate localDate) {
System.out.println(localDate.toString());
// use toString() or format
System.out.println(format(localDate));
}
private String format(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return formatter.format(localDate);
}
public void displayDVD(DVD dvd) {
if (dvd != null) {
io.print(dvd.getTitle());
// format
io.print(format(dvd.getReleaseDate()));
io.print(dvd.getMpaaRating());
io.print(dvd.getDirectorsName());
io.print(dvd.getStudio());
io.print(dvd.getUserRating());
}
}
试试这个。
public void displayDVD(DVD dvd) {
if (dvd != null) {
io.print(dvd.getTitle());
io.print(dvd.getReleaseDate().toString());
io.print(dvd.getMpaaRating());
io.print(dvd.getDirectorsName());
io.print(dvd.getStudio());
io.print(dvd.getUserRating());