Java LocalDate: 补全日期字符串尾部零 (示例代码)
在 Java 中,LocalDate 是一个日期类,用于表示日期。它的 of 方法可以接受年、月、日等参数来创建一个 LocalDate 对象。
要补全 LocalDate 的尾部为 0 的字符,可以使用 String 的 format 方法来格式化日期字符串,然后将其转换为 LocalDate 对象。以下是一个示例程序:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dateStr = '2022-1-1';
// 使用 DateTimeFormatter 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyy-M-d');
// 使用 String 的 format 方法补全尾部为 0 的字符
String formattedDateStr = String.format('%04d-%02d-%02d',
Integer.parseInt(dateStr.substring(0, 4)),
Integer.parseInt(dateStr.substring(5, 6)),
Integer.parseInt(dateStr.substring(7)));
// 将格式化后的字符串转换为 LocalDate 对象
LocalDate date = LocalDate.parse(formattedDateStr, formatter);
System.out.println(date);
}
}
在上面的示例中,我们首先定义了一个日期字符串 dateStr,其格式为 'yyyy-M-d',例如 '2022-1-1'。然后使用 String 的 format 方法将其补全为 '2022-01-01',并将补全后的字符串转换为 LocalDate 对象。最后打印输出该 LocalDate 对象。
输出结果为:
2022-01-01
这样就完成了将尾部为 0 的字符补全的操作。
原文地址: https://www.cveoy.top/t/topic/pmt2 著作权归作者所有。请勿转载和采集!