use*_*250 11 java datetime nio
我正在尝试将文件的creationTime属性转换为日期格式为MM/dd/yyyy的字符串.我正在使用Java nio来获取FileTime类型的creationTime属性,但我只想将此日期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);
Run Code Online (Sandbox Code Playgroud)
但是,它抛出一个异常,说它不能将FileTime date对象格式化为Date.FileTime似乎以2015-01-30T17:30:57.081839Z例如形式输出.你会建议什么解决方案来解决这个问题?我应该在该输出上使用正则表达式还是有更优雅的解决方案?
Sot*_*lis 11
String dateCreated = df.format(date.toMillis());
// ^
Run Code Online (Sandbox Code Playgroud)
Sel*_*raj 11
通过toMillis()方法将FileTime转换为millis .
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);
Run Code Online (Sandbox Code Playgroud)
使用此代码获取格式化值.
在Java 8中,您可以在格式化之前将转换FileTime为ZonedDateTime:
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);
Run Code Online (Sandbox Code Playgroud)
打印:
06/05/2018
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17663 次 |
| 最近记录: |