简体   繁体   English

如何为我已经拥有的时间戳添加分钟?

[英]How to add minutes to a time stamp that I already have?

I searched a lot, but I found a way to add or subtract time from the calendar instance which gives the current time.. how do I subtract time from the last modified time of a given file? 我进行了大量搜索,但是发现了一种从日历实例中添加或减去时间的方法,该方法给出了当前时间。如何从给定文件的上次修改时间中减去时间?

UPDATE : I've been using Java1.4. 更新:我一直在使用Java1.4。 That is the reason I'm unable to find any methods to do this. 这就是我无法找到任何方法执行此操作的原因。 I extracted the modified date as a string. 我将修改后的日期提取为字符串。 I wanted to convert this string obey I a calendar object so that it's easier for me to apply add () of the calendar object to the time. 我想将这个字符串转换为日历对象,以便我可以轻松地将日历对象的add()应用于时间。 I've been facing issues with the same. 我一直在面对同样的问题。 is this approach correct? 这种方法正确吗? Could you please assist 你能帮忙吗

If you dont have to use calendar, than just use the new Java DateTime API available since Java8 https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html 如果您不必使用日历,则只需使用自Java8开始提供的新Java DateTime API https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

There you have very nice convenience methods like plus/minus etc. 那里有非常好的便捷方法,例如加号/减号等。

For example you can simply write 例如,您可以简单地写

  LocalTime now = LocalTime.now();
  now.minusHours(2);

Timestamp (as long ) you can set in Calendar instance. 您可以在Calendar实例中设置时间戳( long )。 And after that you can add() time. 之后,您可以add()时间。

public void time() {
    long timeStamp = 31415926535L;

    Calendar calendar = Calendar.getInstance();

    calendar.setTimeInMillis(timeStamp);

    // Substract 1 hour
    calendar.add(Calendar.HOUR, -1);

    // Add 20 minutes
    calendar.add(Calendar.MINUTE, 20);
}

NIO and java.time 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);

Running just now on my computer I got this output: 刚在我的计算机上运行,​​我得到以下输出:

Time after subtraction is 2017-02-18T03:06:04Z 减去后的时间是2017-02-18T03:06:04Z

The Z at the end indicates UTC . 末尾的Z表示UTC Instant::toString (implicitly called when appending the Instant to a string) always generates a string in UTC. Instant::toString (在将Instant添加到字符串时隐式调用)始终以UTC生成字符串。

I am using the modern Java NIO API and java.time , the modern Java date and time API. 我正在使用现代Java NIO API和现代Java日期和时间API java.time NIO gives us a FileTime in this case denoting the time the file was last modified. NIO在这种情况下为我们提供了FileTime ,它表示文件的最后修改时间。 In order to do our time math I first convert it to an Instant , which is a central class of java.time. 为了进行时间数学计算,我首先将其转换为Instant ,这是java.time的中心类。 The minus method of an Instant subtracts a Duration , an amount of time, and returns a new Instant object. Instantminus方法减去Duration ,一个时间量并返回一个新的Instant对象。

Don't use Calendar . 不要使用Calendar That class was poorly designed and is long outdated. 该课程的设计不佳,已经过时了。

Link: Oracle tutorial: Date Time explaining how to use java.time. 链接: Oracle教程:Date Time说明如何使用java.time。

Since Java 8, java.util.Date , java.util.Calendar , and java.text.SimpleDateFormat are now legacy. 从Java 8开始, java.util.Datejava.util.Calendarjava.text.SimpleDateFormat现在已成为旧版。 So I edit my codes, remove the legacy classes. 因此,我编辑代码,删除旧类。

Thanks @Ole VV and @Basil Bourque for pointing my problems. 感谢@Ole VV和@Basil Bourque指出了我的问题。


I'm confused about your issue. 我对您的问题感到困惑。 I guess you want to modify a file's last modified time. 我猜您想修改文件的上次修改时间。

So I write down the codes. 所以我写下了代码。

import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class Test {

  private static final long ONE_SECOND = 1000L;
  private static final long ONE_MINUTE = 60L * ONE_SECOND;

  public static void main(String[] args) {
    File file = new File("test.txt");
    if (!file.exists()) {
      System.err.println("File doesn't exist.");
      return;
    }

    //get file's last modified, in millisecond
    long timestamp = file.lastModified();
    System.out.println("File's last modified in millisecond: " + timestamp);

    //print time for human, convert to LocalDateTime
    LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
    System.out.println("File's last modified in LocalDateTime: " + localDateTime);

    //add a minute
    timestamp = timestamp + ONE_MINUTE;

    //modify file's last modified
    boolean isModified = file.setLastModified(timestamp);
    if (isModified) {
      System.out.println("Update file's last modified successfully.");
      System.out.println("File's last modified in millisecond: " + file.lastModified());
      //print time for human, convert to LocalDateTime
      System.out.println("File's last modified in LocalDateTime: " +
          LocalDateTime.ofInstant(Instant.ofEpochMilli(file.lastModified()), ZoneId.systemDefault()));
    } else {
      System.err.println("Update file's last modified failed.");
    }
  }

}

Besides, If you want modify a timestamp, just use +/- operations. 此外,如果要修改时间戳,只需使用+/-操作即可。

And you can convert timestamp to LocalDateTime, and use LocalDateTime's api to modify time easily. 您可以将时间戳转换为LocalDateTime,并使用LocalDateTime的api轻松修改时间。

public void modifyTime() {
  //modify timestamp: add one second
  long timestamp = System.currentTimeMillis();
  timestamp = timestamp + 1000L;

  //convert timestamp to LocalDateTime
  LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());

  //modify LocalDateTime
  //add a minute
  localDateTime = localDateTime.plusMinutes(1);
  //subtract a second
  localDateTime = localDateTime.minusSeconds(1);
}

If I misunderstood your idea, please let me know. 如果我误解了您的想法,请告诉我。

You can use setTime() like this: 您可以像这样使用setTime():

yourTimeStamp.setTime(yourTimeStamp.getTime() + TimeUnit.MINUTES.toMillis(minutesToAdd)); yourTimeStamp.setTime(yourTimeStamp.getTime()+ TimeUnit.MINUTES.toMillis(minutesToAdd));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM