首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用FileTime将DateFormat转换为字符串

如何使用FileTime将DateFormat转换为字符串
EN

Stack Overflow用户
提问于 2015-02-03 17:09:24
回答 5查看 27K关注 0票数 11

我试图将文件的creationTime属性转换为日期格式为MM/dd/yyyy的字符串。我正在使用Java获取creationTime属性,该属性是FileTime类型的,但我只希望将此FileTime中的日期作为字符串使用前面指定的日期格式。到目前为止我..。

代码语言:javascript
复制
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,还是有一个更优雅的解决方案?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-02-03 17:12:11

只有get the milliseconds since epochFileTime

代码语言:javascript
复制
String dateCreated = df.format(date.toMillis());
//                                 ^
票数 14
EN

Stack Overflow用户

发布于 2015-02-03 17:17:38

用FileTime方法将toMillis()转换成millis。

代码语言:javascript
复制
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);

使用此代码获取格式化值。

票数 12
EN

Stack Overflow用户

发布于 2018-06-05 12:58:10

在Java8中,您可以在格式化FileTime之前将它转换为ZonedDateTime

代码语言:javascript
复制
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);

其中的指纹:

代码语言:javascript
复制
06/05/2018
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28304751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档