示例:
LocalDate today = LocalDate.now();
LocalDate lastMonth = today.minusMonths(1);
LocalDate lastDay = lastMonth.with(TemporalAdjusters.lastDayOfMonth());
LocalDate firstDay = lastMonth.with(TemporalAdjusters.firstDayOfMonth());
String a = "1";
String s = a + firstDay;
System.out.println(s);
你应该知道,两个不同的类型进行相加操作的时候,类型会自动转换吧
比如int+float,那么int类型的变量会先隐式转换成float类型,再进行float类型的加法操作
float+double,int+long,都是类似的
整型向浮点型靠拢,小类型会向大类型靠拢,有符号类型会向无符号类型靠拢
那么string型和其他类型相加,其他类型会自动转成string类型,此时会自动调用其他类型的toString()方法
toString方法定义在object中,是所有类型的基类
如果类型没有重写toString,那么默认返回类型的名称
如果重写了,那么返回的是值的字符串表示
LocalDate类重写了toString()方法,返回一个字符串表示形式。所以,当做字符串拼接时,LocalDate对象会自动调用toString()方法,将其转换为字符串。
使用 +拼接的时候就会默认调用对象的toString方法,实际可以理解是 String s = a + firstDay.toString();
可以使用加号符号"+"将Java LocalDate对象的日期与String对象进行拼接。具体步骤如下:
示例代码如下:
LocalDate localDate = LocalDate.now();
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String dateStr = localDate.format(dateTimeFormat);
示例代码如下:
String str = "今天是:" + dateStr;
System.out.println(str);
完整示例代码如下:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();
DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String dateStr = localDate.format(dateTimeFormat);
String str = "今天是:" + dateStr;
System.out.println(str); // 输出:今天是:2022-11-07
}
}
输出结果为:"今天是:2022-11-07"。