要让补全 LocalDate 的尾部为0的字符自动省略,你可以使用 DateTimeFormatter 类的 ofPattern 方法来创建一个自定义的日期格式。然后使用该格式来格式化 LocalDate 对象。

以下是一个示例代码:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2022, 3, 4);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyy-M-d');
        String formattedDate = date.format(formatter);

        System.out.println(formattedDate);
    }
}

在上述代码中,我们创建了一个 LocalDate 对象表示2022年3月4日。然后,我们使用自定义的日期格式'yyyy-M-d'创建了一个 DateTimeFormatter 对象。这个格式中的'M'和'd'分别表示月份和日期,不带前导零。最后,我们使用 format 方法将 LocalDate 对象格式化为字符串,并打印输出。

输出结果为:2022-3-4

注意:如果你希望补全 LocalDate 的尾部为0的字符自动省略,你需要确保传入的日期值没有前导零。如果你的日期值中有前导零,那么它们将被保留在格式化后的字符串中。


原文地址: https://www.cveoy.top/t/topic/pmtW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录