Close

Java - Converting FileTime To Formatted String and vice versa

[Updated: Feb 11, 2019, Created: Feb 6, 2019]

Java Date Time Java 

Following example shows how to convert FileTime to a formatted String and vice-versa:

package com.logicbig.example;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class FileTimeToFormattedString {
  private static final DateTimeFormatter DATE_FORMATTER_WITH_TIME = DateTimeFormatter
          .ofPattern("MMM d, yyyy HH:mm:ss.SSS");

  public static String fileTimeToString(FileTime fileTime) {
      String s = parseToString(
              fileTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
      return s;
  }

  public static FileTime fileTimeFromString(String dateTimeString) {
      LocalDateTime localDateTime = parseFromString(dateTimeString);
      return FileTime.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
  }

  public static String parseToString(LocalDateTime localDateTime) {
      return localDateTime.format(DATE_FORMATTER_WITH_TIME);
  }

  public static LocalDateTime parseFromString(String date) {
      return LocalDateTime.parse(date, DATE_FORMATTER_WITH_TIME);
  }

  public static void main(String[] args) throws IOException {
      //create a file
      Path path = Files.createTempFile("test", ".txt");
      System.out.println(path);
      System.out.println(Files.exists(path));
      path.toFile().deleteOnExit();
      //get creation time
      BasicFileAttributes bfa = Files.readAttributes(path, BasicFileAttributes.class);
      FileTime fileTime = bfa.creationTime();
      System.out.println("fileTime: " + fileTime);
      //convert creation time to string
      String s = fileTimeToString(fileTime);
      System.out.println("FileTime toString: " + s);

      FileTime fileTime1 = fileTimeFromString(s);
      System.out.println("FileTime fromString: " + fileTime1);
  }
}
C:\Users\Joe\AppData\Local\Temp\test1293045960670637876.txt
true
fileTime: 2019-02-11T08:35:20.318203Z
FileTime toString: Feb 11, 2019 02:35:20.318
FileTime fromString: 2019-02-11T08:35:20.318Z

Above example can also be used to convert FileTime to LocalDateTime and vice versa.

See Also