Java 8 获取当前日期 (含中文格式)
Java 8 获取当前日期 (含中文格式)
Java 8 提供了 LocalDate 类来获取当前日期,并使用 DateTimeFormatter 类设置日期格式,包括中文。
示例代码:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// 设置日期格式为中文
DateTimeFormatter formatter = DateTimeFormatter.ofPattern('yyyy年MM月dd日', Locale.CHINA);
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 格式化日期并输出
String formattedDate = currentDate.format(formatter);
System.out.println(formattedDate);
}
}
输出结果:
2023年03月15日
解释:
-
DateTimeFormatter的ofPattern()方法接收一个字符串作为参数,该字符串指定了日期格式。在本例中,我们使用了中文格式,即 'yyyy年MM月dd日'。 -
Locale.CHINA指定了使用中文语言环境。 -
LocalDate.now()获取当前日期。 -
currentDate.format(formatter)将当前日期格式化为字符串。 -
System.out.println()打印输出结果。
总结:
通过使用 LocalDate 和 DateTimeFormatter 类,我们可以轻松地获取当前日期并将其格式化为所需的中文格式。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/orF4 著作权归作者所有。请勿转载和采集!