租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

java如何获取指定格式日期,java获取指定位置字符

发布时间:2023-10-12 19:01:25

java如何获得指定格式日期

要获得指定格式的日期,可使用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",你可以根据需要修改日期格式。