在Java中,可以使用java.time包下的LocalDateTime类来获取当前的日期和时间,并将其转换为指定的格式。

首先,导入java.time包:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

然后,使用LocalDateTime.now()方法获取当前日期和时间,并使用DateTimeFormatter类的ofPattern()方法来定义日期和时间的格式:

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

接下来,使用format()方法将LocalDateTime对象按照指定的格式转换为字符串:

String formattedDateTime = now.format(formatter);

最后,将字符串命名为文件名:

String fileName = formattedDateTime + ".txt";
System.out.println(fileName);

运行以上代码,将输出类似于"2023-08-31 10:30:20.txt"的文件名。

注意:文件名中不能包含特殊字符,如"/"、":"等,否则会导致文件系统无法识别该文件名。因此,可以使用其他字符替换这些特殊字符,以确保文件名的有效性

文件最好怎么以年月日时分秒命名java可以很好拿到 2023-08-31 和 103020

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

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