我试图将文件的creationTime属性转换为日期格式为MM/dd/yyyy的字符串。我正在使用Java获取creationTime属性,该属性是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 date对象格式化为日期。例如,FileTime似乎以2015-01-30T17:30:57.081839Z的形式输出。您推荐什么样的解决方案来最好地解决这个问题?我应该只是在输出上使用regex,还是有一个更优雅的解决方案?
发布于 2015-02-03 17:12:11
只有get the milliseconds since epoch从FileTime。
String dateCreated = df.format(date.toMillis());
// ^发布于 2015-02-03 17:17:38
用FileTime方法将toMillis()转换成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);使用此代码获取格式化值。
发布于 2018-06-05 12:58:10
在Java8中,您可以在格式化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);其中的指纹:
06/05/2018https://stackoverflow.com/questions/28304751
复制相似问题