View Javadoc
1   /*
2    * Copyright (C) 2019, Matthias Sohn <matthias.sohn@sap.com> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.junit.time;
11  
12  import java.io.IOException;
13  import java.io.UncheckedIOException;
14  import java.nio.file.Files;
15  import java.nio.file.Path;
16  import java.nio.file.attribute.FileTime;
17  import java.time.Instant;
18  
19  import org.eclipse.jgit.util.FS;
20  
21  /**
22   * Utility methods for handling timestamps
23   *
24   * @since 5.1.9
25   */
26  public class TimeUtil {
27  	/**
28  	 * Set the lastModified time of a given file by adding a given offset to the
29  	 * current lastModified time
30  	 *
31  	 * @param path
32  	 *            path of a file to set last modified
33  	 * @param offsetMillis
34  	 *            offset in milliseconds, if negative the new lastModified time
35  	 *            is offset before the original lastModified time, otherwise
36  	 *            after the original time
37  	 * @return the new lastModified time
38  	 */
39  	public static Instant setLastModifiedWithOffset(Path path,
40  			long offsetMillis) {
41  		Instant mTime = FS.DETECTED.lastModifiedInstant(path)
42  				.plusMillis(offsetMillis);
43  		try {
44  			Files.setLastModifiedTime(path, FileTime.from(mTime));
45  			return mTime;
46  		} catch (IOException e) {
47  			throw new UncheckedIOException(e);
48  		}
49  	}
50  
51  	/**
52  	 * Set the lastModified time of file a to the one from file b
53  	 *
54  	 * @param a
55  	 *            file to set lastModified time
56  	 * @param b
57  	 *            file to read lastModified time from
58  	 */
59  	public static void setLastModifiedOf(Path a, Path b) {
60  		Instant mTime = FS.DETECTED.lastModifiedInstant(b);
61  		try {
62  			Files.setLastModifiedTime(a, FileTime.from(mTime));
63  		} catch (IOException e) {
64  			throw new UncheckedIOException(e);
65  		}
66  	}
67  
68  }