温馨提示×

java怎么获取指定格式日期

小亿
111
2023-10-12 19:01:25
栏目: 编程语言

要获取指定格式的日期,可以使用java.time包中的DateTimeFormatter类。下面是一个示例代码,演示如何获取指定格式的日期:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 创建一个日期格式化器,指定要获取的日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 使用日期格式化器将日期转换为指定格式的字符串
String formattedDate = currentDate.format(formatter);
// 输出结果
System.out.println("Formatted Date: " + formattedDate);
}
}

在上面的代码中,我们首先获取当前日期LocalDate.now(),然后创建一个日期格式化器DateTimeFormatter,并使用ofPattern方法指定要获取的日期格式。最后,使用format方法将日期转换为指定格式的字符串。输出结果将显示格式化后的日期。

在这个示例中,我们将日期格式指定为"yyyy-MM-dd",你可以根据需要修改日期格式。

0