我搜索了很多,但我找到了一种从给出当前时间的日历实例中添加或减去时间的方法。如何从给定文件的上次修改时间中减去时间?
更新: 我一直在使用Java1.4。这就是我无法找到任何方法来做到这一点的原因。 我将修改日期提取为字符串。我想将此字符串转换为日历对象,以便我更容易将日历对象的 add() 应用于时间。我也遇到过同样的问题。这种做法正确吗?您能帮忙吗
最佳答案
NIO 和 java.time
Path filePath = Paths.get("myFile.txt");
Duration timeToSubtract = Duration.ofMinutes(7);
FileTime lastModified = Files.getLastModifiedTime(filePath);
Instant lastModifiedInstant = lastModified.toInstant();
Instant timeBeforeLastModified = lastModifiedInstant.minus(timeToSubtract);
System.out.println("Time after subtraction is " + timeBeforeLastModified);
刚刚在我的计算机上运行,我得到了以下输出:
Time after subtraction is 2017-02-18T03:06:04Z
末尾的 Z
表示 UTC 。 Instant::toString
(将 Instant
附加到字符串时隐式调用)始终生成 UTC 格式的字符串。
我正在使用现代的 Java NIO API和 java.time ,现代 Java 日期和时间 API。 NIO给我们一个FileTime
在本例中表示文件上次修改的时间。为了进行时间数学计算,我首先将其转换为 Instant
,它是java.time的中心类。 Instant
的 minus
方法减去 Duration
,一段时间,并返回一个新的 Instant
对象。
不要使用日历
。该类设计得很糟糕并且早已过时。
链接: Oracle tutorial: Date Time解释如何使用 java.time。
关于java - 如何向我已有的时间戳添加分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55100424/