JavaLlocalDate对象

为什么LocalDate对象可以直接与String对象进行拼接

示例:

        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();

  • 这篇文章:Java8时间 实体类使用LocalDate接收String字符串时间 小记 也许能够解决你的问题,你可以看下
  • 以下回答由chatgpt基于相关博客总结生成:

    可以使用加号符号"+"将Java LocalDate对象的日期与String对象进行拼接。具体步骤如下:

    1. 将LocalDate对象转换为String类型,可以使用DateTimeFormatter类的format方法将LocalDate格式化为String类型。

    示例代码如下:

    LocalDate localDate = LocalDate.now();
    DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String dateStr = localDate.format(dateTimeFormat);
    
    1. 将需要拼接的String类型与上述字符串相加。

    示例代码如下:

    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"。