Java 如何使用DateFormat将FileTime转换为字符串
我正在尝试将文件的creationTime属性转换为日期格式为MM/dd/yyyy的字符串。我正在使用Java nio获取creationTime属性,该属性属于Java 如何使用DateFormat将FileTime转换为字符串,java,datetime,nio,Java,Datetime,Nio,我正在尝试将文件的creationTime属性转换为日期格式为MM/dd/yyyy的字符串。我正在使用Java nio获取creationTime属性,该属性属于FileTime类型,但我只想将此FileTime中的日期作为一个字符串,使用前面指定的日期格式。到目前为止我已经 String file = "C:\\foobar\\example.docx"; Path filepath = Paths.get(file); BasicFileAttributes attr = Files.rea
FileTime
类型,但我只想将此FileTime
中的日期作为一个字符串,使用前面指定的日期格式。到目前为止我已经
String file = "C:\\foobar\\example.docx";
Path filepath = Paths.get(file);
BasicFileAttributes attr = Files.readAttributes(filepath,BasicFileAttributes.class);
FileTime date = attr.creationTime();
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateCreated = df.format(date);
但是,它抛出一个异常,表示无法将FileTime日期
对象格式化为日期。例如,FileTime似乎以2015-01-30T17:30:57.081839Z的形式输出。您会推荐什么解决方案来最好地解决此问题?我应该在该输出上使用regex还是有更优雅的解决方案?仅从FileTime
开始
String dateCreated = df.format(date.toMillis());
// ^
通过toMillis()
方法将文件时间转换为毫秒
String file = "C:\\foobar\\example.docx";
Path filepath = Paths.get(file);
BasicFileAttributes attr = Files.readAttributes(filepath, BasicFileAttributes.class);
FileTime date = attr.creationTime();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateCreated = df.format(date.toMillis());
System.out.println(dateCreated);
使用此代码获取格式化的值 将文件时间转换为日期
Path path = Paths.get("C:\\Logs\\Application.evtx");
DateFormat df=new SimpleDateFormat("dd/MM/yy");
try {
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
Date d1 = df.parse(df.format(attr.creationTime().toMillis()));
System.out.println("File time : " +d1);
} catch (Exception e) {
System.out.println("oops error! " + e.getMessage());
}
使用此代码转换在Java 8中,您可以在格式化前将文件时间
转换为分区日期时间
:
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
long cTime = attr.creationTime().toMillis();
ZonedDateTime t = Instant.ofEpochMilli(cTime).atZone(ZoneId.of("UTC"));
String dateCreated = DateTimeFormatter.ofPattern("MM/dd/yyyy").format(t);
System.out.println(dateCreated);
其中打印:
06/05/2018
总结如下:
String file = "C:\\foobar\\example.docx";
Path filepath = Paths.get(file);
BasicFileAttributes attr = Files.readAttributes(filepath,BasicFileAttributes.class);
FileTime date = attr.creationTime();
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateCreated = df.format(date.toMillis());
你不必使用toMillis()
然后再使用Instant.ofEpochMillis()
你只需使用FileTime
类的toInstant()
。@cbley我最初也提出了FileTime#toInstant()
,但后来出现了bug,所以我改了。但是我已经不记得原因了……但是在转换为毫秒时,可能会失去精度(如果FileTime具有纳秒精度)。我真的很想知道那里有什么样的虫子…@cbley和@Mi@MincongHuangdateTimeFormatter.format(fileTime.toInstant())
引发异常java.time.temporal.UnsupportedTemporalTypeException:Unsupported字段:Year
@VenkataRaju:如果要格式化即时
,必须提供时区,否则格式化程序无法决定如何呈现信息:dateTimeFormatter.format(fileTime.toInstant().atZone(ZoneOffset.UTC))
只需更改底部的最后一行即可